chr*_*244 12 c++ variadic-templates c++11
Jonathan Wakely 对问题的回答类型特征检查参数包中的所有类型是否是可复制构造的,这提供了一种简单的(ish)方法来检查参数包中扩展的所有变量是否属于同一类型 - 例如:
#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>...>;
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何扩展它,例如areTypeT,编写一个模板.
我的第一次尝试偶然发现"参数包'T'必须位于模板参数列表的末尾".我最近的尝试编译,但如果我使用它然后我得到替换失败:
template<typename Target>
template<typename... T1>
using areT = and_<std::is_same<T1,Target>...>;
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
您的语法稍微偏离,您不需要两个单独的模板声明,该语法用于定义类外的成员模板:
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");
Run Code Online (Sandbox Code Playgroud)
C ++ 17定义了标准库的标头中定义的and_被调用版本。std::conjunction<type_traits>
template <typename T, typename ...Ts>
using areT = std::conjunction<std::is_same<T,Ts>...>;
static_assert(areT<int,int,int,int>::value);
Run Code Online (Sandbox Code Playgroud)
还有一个std::conjunction叫做的版本,std::conjunction_v它提供了value其实例化的数据成员。因此,您也可以areT_v自己定义C ++ 14变量模板:
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>);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2242 次 |
| 最近记录: |