我正在寻找一种模式将C++类型特征转换为它们的可变参数.一个方法来解决这个问题,将不胜感激,并生成编程模式,以自动执行任务将是理想的.
请考虑以下事项:
std::is_same<T, U>::value;
Run Code Online (Sandbox Code Playgroud)
我想写一个像这样的特征:
std::are_same<T1, T2, T3, T4>::value;
Run Code Online (Sandbox Code Playgroud)
实现这个非常简单are_same ; 寻求一般解决方案,我们可以为任何实现通用量化的可变特性提供工具:
template<template<class,class> class F, typename...Ts>
struct Univ;
template<template<class, class> class F, typename T, typename U, typename...Ts>
struct Univ<F, T, U, Ts...>
{
static const int value = F<T, U>::value && Univ<F, U, Ts...>::value;
};
template<template<class, class> class F, typename T>
struct Univ<F, T>
{
static const int value = 1;
};
Run Code Online (Sandbox Code Playgroud)
所以,例如are_same …
c++ templates generative-programming template-meta-programming 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)
我怎样才能做到这一点?
例如,我想T只在它是std::is_pointer<T>和时使用类型std::is_const<T>.
当然,有这样简单的方法:
template <typename T>
void f(T t, std::true_type, std::true_type) {}
template <typename T>
void f(T t)
{
f(t, std::is_pointer<T>{}, std::is_const<T>{});
}
Run Code Online (Sandbox Code Playgroud)
但是我想要这样的东西:
template <typename T>
void f(T t, std::true_type) {}
template <typename T>
void f(T t)
{
f(t, std::and<std::is_pointer<T>, std::is_const<T>>{});
}
Run Code Online (Sandbox Code Playgroud)
在c ++标准类中是什么样的true_type?如果不是,是否有任何简单的方法来实现它,具有所需的功能?
我可以创建一个只接受指针的可变参数模板:
template<typename ... Types>
void F(Types *... args);
Run Code Online (Sandbox Code Playgroud)
或者只接受引用的可变参数模板:
template<typename ... Types>
void F(Types &... args);
Run Code Online (Sandbox Code Playgroud)
如何创建一个接受非const引用或指针的模板?
例如
int a, b, c;
F(a, &b); // => F<int &, int *>
F(a, 3); // Error, 3 not pointer and cannot bind to non const-reference
Run Code Online (Sandbox Code Playgroud)
注意:参考版本可能看起来没问题,因为它可以绑定到指针引用但不是因为它不会绑定到 int * const