出于教育目的,我想写自己c++11的类型列表.裸列表看起来像这样:
template <typename ... Ts> struct type_list;
template <typename T, typename ... Ts>
struct type_list<T, Ts ...> {
typedef T Head;
typedef type_list<Ts ...> Tail;
};
template <typename T> struct type_list<T> {
typedef T Head;
typedef null_type Tail;
};
Run Code Online (Sandbox Code Playgroud)
我创建了一个调用front提取第一个元素的函数:
template <typename T> struct front;
template <typename TypeList>
struct front {
typedef typename TypeList::Head type;
};
Run Code Online (Sandbox Code Playgroud)
哪个按预期工作,即此代码
typedef type_list<int> lst;
typedef type_list<float,int> lst2;
typedef type_list<double,float,int> lst3;
typedef type_list<char,double,float,int> lst4;
std::cout << "front(lst1): " << typeid( front<lst>::type …Run Code Online (Sandbox Code Playgroud) c++ templates metaprogramming template-meta-programming c++11
如果我们有类似的模板元函数std::conditional,我们可以根据布尔编译时条件"选择"类型.例如:
template < bool CONDITION, typename T, typename U >
struct conditional;
template < typename T, typename U >
struct conditional < true, T, U >
{
using type = T;
};
template < typename T, typename U >
struct conditional < false, T, U >
{
using type = U;
};
const bool whats_big = sizeof( int ) > sizeof( double );
using bigger_type = typename conditional<whats_big , int , double>::type;
Run Code Online (Sandbox Code Playgroud)
我的问题是:有没有办法在有效类型和无效类型之间进行选择?
我目前正在实施一个活动类.事件具有sender参数和可变数量的事件args:
template<typename SENDER , …Run Code Online (Sandbox Code Playgroud) 我工作的一个简单的解决方案,以共同的"上形成不良的类型条件"的问题(像这个昨天的问题).
在我的代码库中,我有一个模板来保存未实例化的模板并在以后实例化它们.像这样的东西:
template<template<typename...> class F>
struct lazy
{};
namespace impl
{
template<typename L , typename... ARGS>
struct lazy_instance;
template<template<typename...> class F , typename... ARGS>
struct lazy_instance<lazy<F>,ARGS...> : public identity<F<ARGS...>>
{};
}
template<typename L , typename... ARGS>
using lazy_instance = typename impl::lazy_instance<L,ARGS...>::type;
Run Code Online (Sandbox Code Playgroud)
identity身份元功能在哪里.
这可以使用如下:
using vector = lazy<std::vector>;
using int_vector = lazy_instance<vector,int>;
Run Code Online (Sandbox Code Playgroud)
因此,我想到的解决方案是以这种方式包装条件的两个目标,并实例化条件的结果,因此只有选定的模板才会被实例化.为此,我修改了lazy并impl::lazy_instance允许我们在lazy瞬间点传递模板参数:
template<template<typename...> class F , typename... ARGS>
struct lazy
{};
namespace impl
{
template<typename L , typename... ARGS> …Run Code Online (Sandbox Code Playgroud)