本文介绍了检查是否在可变参数模板参数包中传递类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在某处听说过,使用新的C ++ 1z语法,很容易检查是否在可变参数模板参数包中传递了类型-显然,您可以使用接近一行的代码来完成此操作。这是真的?有哪些相关功能? (我尝试查看折叠表达式,但看不到如何在该问题中使用它们...)
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;
};
推荐答案
您在寻找。在 中指定[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>());
或适应结构
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>{} || ...)>
{};
这篇关于检查是否在可变参数模板参数包中传递类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!