Search code examples
c++templatesc++14typedefmaintainability

avoid duplicated code : typedef/using a template class that has default parameter (C++14)


How to define an alias name of a template class that has default template parameter without code duplication?

Does C++14 improve it in some ways?

In a real case, it really causes maintainability problem. (demo)

class B{};
template<class T1,class T2,class T3=B>class E{};   //<- "class T3=B"
//^ library

//v user
class C{};
template<class T1,class T3=B> using F=E<T1,C,T3>;  //<- "class T3=B" is duplicated
int main() {
    F<B> f1;
    F<B,C> f2;
    return 0;
}

Workaround

In old C++, there is no elegant solution.
Here is the best workaround, modified from Using a typedefed default type for template parameter :-

class B{};
using E_T3_default=B;
template<class T1,class T2,class T3=E_T3_default>class E{}; //<-
//^ library

//v user
class C{};
template<class T1,class T3=E_T3_default> using F=E<T1,C,T3>;  //<- 

My dream

I hope for something like:-

template<class T1,class T3> using F=E<T1,C,T3>;

and F<B> will be expanded to E<B,C,B(default)> automatically (not compile error).


Solution

  • You can make use of a parameter pack:

    template <class T1, class... T3>
    using F = E<T1, C, T3...>;
    

    ... to directly forward zero or one argument to E.