Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one use template specialization on a templated typedef?

I would like to do something like the following (in c++11, c++14; not c++17):

template <class T>
using partner = void;

template<>
using partner<A> = X;

template<>
using partner<B> = Y;

template<>
using partner<C> = Z;

But I get a compilation error---

error: expected unqualified-id before ‘using’

---on the first template specialization.

Is such a thing possible? (I already know I can use a templated class with a using statement inside it. I'm hoping directly use the using statement without the class wrapper, since it's simpler and more elegant. If there's another simple, elegant solution, please share!)

like image 202
DanielGr Avatar asked Dec 24 '22 13:12

DanielGr


1 Answers

You can't specialize alias templates.

You'll have to resort to normal, boring class template specialization:

template <class T> struct partner_t { using type = void; };
template <> struct partner_t<A> { using type = X; };
template <> struct partner_t<B> { using type = Y; };
template <> struct partner_t<C> { using type = Z; };

template <class T>
using partner = typename partner_t<T>::type;

Or we could get fancier

template <class T> struct tag { using type = T; };

template <class T> auto partner_impl(tag<T> ) -> tag<void>;
auto partner_impl(tag<A> ) -> tag<X>;
auto partner_impl(tag<B> ) -> tag<Y>;
auto partner_impl(tag<C> ) -> tag<Z>;

template <class T>
using partner = typename decltype(partner_impl(tag<T>{}))::type;
like image 179
Barry Avatar answered Mar 20 '23 19:03

Barry