gexicide
gexicide

Reputation: 40128

using template specialization

Usual template structs can be specialized, e.g.,

template<typename T>
struct X{};

template<>
struct X<int>{};

C++11 gave us the new cool using syntax for expressing template typedefs:

template<typename T>
using YetAnotherVector = std::vector<T>

Is there a way to define a template specialization for these using constructs similar to specializations for struct templates? I tried the following:

template<>
using YetAnotherVector<int> = AFancyIntVector;

but it yielded a compile error. Is this possible somehow?

Upvotes: 14

Views: 3158

Answers (3)

iamacomputer
iamacomputer

Reputation: 565

There is another pattern which I prefer over the std::conditional. Maybe you'll prefer it as well.

It looks like this:

struct MyAwesomeVector {};

// this is the default 
template<typename T>
struct VectorSpecialization {
    typedef std::vector<T> Type;
} ;

// this is your awesomeness for int
template<>
struct VectorSpecialization<int> {
    typedef MyAwesomeVector Type;
} ;

// this is the using declaration
template<typename T>
using MyVector = typename VectorSpecialization<T>::Type;

Upvotes: 0

Columbo
Columbo

Reputation: 61009

It's neither possible to specialize them explicitly nor partially. [temp.decls]/3:

Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.

You will have to defer specializations to class templates. E.g. with conditional:

template<typename T>
using YetAnotherVector = std::conditional_t< std::is_same<T, int>{}, 
                                             AFancyIntVector, 
                                             std::vector<T> >;

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361792

No.

But you can define the alias as:

template<typename T>
using YetAnotherVector = typename std::conditional<
                                     std::is_same<T,int>::value, 
                                     AFancyIntVector, 
                                     std::vector<T>
                                     >::type;

Hope that helps.

Upvotes: 11

Related Questions