C ++ 1z - 检查是否在可变参数模板参数包中传递了类型 [英] C++1z - Check if a type is passed in variadic template parameter pack
问题描述
我听说过某个地方,使用新的C ++ 1z语法,很容易检查一个类型是否在variadic模板参数包中传递 - 显然你可以使用接近一行长的代码。这是真的?这些相关的功能是什么? (我尝试查看折叠表达式,但我不能看到如何使用它们在该问题...)
I've heard somewhere, that using new C++1z syntax, it is really easy to check if a type is passed in variadic template parameter pack - apparently you can do this with code that is near one-line long. Is this true? What are those relevant features? (I tried looking through fold expressions but I can't see how to use them in that problem...)
这是我如何解决问题在C + + 11供参考:
Here's how I solved the problem in C++11 for reference:
#include <type_traits>
template<typename T, typename ...Ts>
struct contains;
template<typename T>
struct contains<T> {
static constexpr bool value = false;
};
template<typename T1, typename T2, typename ...Ts>
struct contains<T1, T2, Ts...> {
static constexpr bool value = std::is_same<T1, T2>::value ? true : contains<T1, Ts...>::value;
};
推荐答案
您正在查找 std :: disjunction
。它在 N4564 中指定 [meta.logical]
You're looking for std::disjunction
. It's specified in N4564 [meta.logical].
#include <type_traits>
template<typename T, typename... Ts>
constexpr bool contains()
{ return std::disjunction_v<std::is_same<T, Ts>...>; }
static_assert( contains<int, bool, char, int, long>());
static_assert( contains<bool, bool, char, int, long>());
static_assert( contains<long, bool, char, int, long>());
static_assert(not contains<unsigned, bool, char, int, long>());
或适用于 struct
template<typename T, typename... Ts>
struct contains : std::disjunction<std::is_same<T, Ts>...>
{};
或使用折叠表达式
Or, using fold expressions
template<typename T, typename... Ts>
struct contains : std::bool_constant<(std::is_same<T, Ts>{} || ...)>
{};
这篇关于C ++ 1z - 检查是否在可变参数模板参数包中传递了类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!