Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to write a generalized rebind template?

Tags:

c++

c++11

without specializing for each class template/class, is it possible to write a generalized 'rebind' meta function, so that given

 template<class > struct foo;
 struct bar;

the following

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

and maybe

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

returns a type equivalent of true?

like image 239
abir Avatar asked Nov 08 '12 07:11

abir


1 Answers

Sure.

But be aware that any template template parameter taking a variadic template parameter list is restricted to accepting templates with only type parameters, not non-type parameters. In other words, the general case below won't work for std::array because its second argument is an integer. You'd have to add a special case.

The primary template is already a special case, since it handles classes that aren't a specialization of a template.

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;
like image 95
Potatoswatter Avatar answered Oct 11 '22 03:10

Potatoswatter