C++ 检查所有类型T的参数包
Jonathan Wakely的问题解答提供了一种简单(ish)的方法来检查参数包中展开的所有变量是否属于同一类型-例如:C++ 检查所有类型T的参数包,c++,c++11,variadic-templates,C++,C++11,Variadic Templates,Jonathan Wakely的问题解答提供了一种简单(ish)的方法来检查参数包中展开的所有变量是否属于同一类型-例如: #include <type_traits> namespace detail { enum class enabler {}; } template <bool Condition> using EnableIf = typename std::enable_if<Condition, detail::enabler>
#include <type_traits>
namespace detail {
enum class enabler {};
}
template <bool Condition>
using EnableIf =
typename std::enable_if<Condition, detail::enabler>::type;
template<typename... Conds>
struct and_ : std::true_type {};
template<typename Cond, typename... Conds>
struct and_<Cond, Conds...>
: std::conditional<Cond::value, and_<Conds...>,
std::false_type>::type {};
template<typename... T>
using areInts = and_<std::is_same<T,int>...>;
template<typename... T>
using areMySpecificClass = and_<std::is_same<T,MySpecificClass>...>;
我怎样才能做到这一点呢?您的语法有点错误,您不需要两个单独的模板声明,该语法用于在类外定义成员模板:
template<typename Target, typename... Ts>
using areT = and_<std::is_same<Ts,Target>...>;
static_assert(areT<int,int,int,int>::value,"wat");
static_assert(!areT<int,float,int,int>::value,"wat");
模板
使用areT=和ux;
静态断言(areT::value,“wat”);
静态断言(!areT::value,“wat”);
就这样
template<typename Type, typename... T>
using areTypeT = and_<std::is_same<T, Type>...>;
模板
使用areTypeT=和;
C++17定义了标准库中
标题中定义的和
版本,称为std::conjunction
template <typename T, typename ...Ts>
using areT = std::conjunction<std::is_same<T,Ts>...>;
static_assert(areT<int,int,int,int>::value);
模板
constexpr bool all_相同_v=sizeof…(类型)?(标准::是否相同?&&…):错误;
假设空包会导致错误值。有关基于
概念的解决方案,请参阅:什么是(和)?
template <typename T, typename ...Ts>
using areT = std::conjunction<std::is_same<T,Ts>...>;
static_assert(areT<int,int,int,int>::value);
template <typename T, typename ...Ts>
inline constexpr bool areT_v = std::conjunction_v<std::is_same<T,Ts>...>;
static_assert( areT_v<int,int,int,int>);
static_assert(!areT_v<int,int,int,char>);
template <typename ... Types>
constexpr bool all_same_v = sizeof...(Types) ? (std::is_same_v<std::tuple_element_t<0, std::tuple<Types...>>, Types> && ...) : false;