Search code examples
c++templatesreturn-typearithmetic-expressions

Specializing variadic template with using


Good evening,

I am having trouble with specialzing a variadic template. I need the following template:

template<typename... Ts>
using OPT = decltype(operator+(std::declval<Ts>()...))(Ts...);

The problem is, this doesn't compile, when I try to use

OTP<double,double>

so I've tried specializing it via

template<>
using OPT<double,double> = double;

But now I get the error

error: expected unqualified-id before ‘using’
using OPT<double,double> = double;

Does anybody know a way around this or am I doing something wrong?

Thank you for reading and helping!


Solution

  • You need a struct behind the hood to implement this, since alias templates can't be specialized and can't refer to themselves.

    #include <utility>
    
    template<typename T, typename... Ts>
    struct sum_type {
        using type = decltype(std::declval<T>() + std::declval<typename sum_type<Ts...>::type>());
    };
    
    template <typename T>
    struct sum_type<T> {
        using type = T;
    };
    
    template<typename... Ts>
    using OPT = typename sum_type<Ts...>::type;
    

    Demo.