是否可以编写通用的重新绑定模板?

时间:2012-11-08 07:22:05

标签: c++ c++11

没有专门针对每个类模板/类,是否可以编写一个通用的'rebind'元函数,以便 给定

 template<class > struct foo;
 struct bar;

以下

 is_same<rebind<foo<int>,float>,foo<float>> 
 is_same<rebind<bar>,bar>

也许

is_same< rebind<std::vector<int>,float>,std::vector<float>>  

返回类似于true的类型?

1 个答案:

答案 0 :(得分:6)

不确定

但请注意,采用可变参数模板参数列表的任何模板模板参数仅限于接受仅包含类型参数的模板,而不是非类型参数。换句话说,下面的一般情况不适用于std::array,因为它的第二个参数是一个整数。你必须添加一个特例。

主模板已经是一种特殊情况,因为它处理不是模板特化的类。

http://liveworkspace.org/code/5b6f0cb3aec1eb74701e73d8d21aebab

template< typename bound, typename ... new_args >
struct rebind_class {
    static_assert( sizeof ...( new_args ) == 0,
         "can't rebind arguments to non-specialization" );
    typedef bound type;
};

template< template< typename ... > class template_, typename ... new_args,
    typename ... old_args >
struct rebind_class< template_< old_args ... >, new_args ... > {
    typedef template_< new_args ... > type;
};

template< typename ... args >
using rebind = typename rebind_class< args ... >::type;
相关问题