Home > Back-end >  Pattern matching with variadic templates and default argument
Pattern matching with variadic templates and default argument

Time:03-31

I'm trying to add a default "hidden" setting into a templated class:

template<bool DebugMode=false, typename... Args>
struct A
{
        A() {};
};

int main()
{
    A<double, double> a;
}

which fails when compile with g 8.3.1 and C 17:

error: type/value mismatch at argument 1 in template parameter list for ‘template<bool DebugMode, class ... Args> struct A’
note:  expected a constant of type ‘bool’, got ‘double’

Yet I don't understand why g can't do any pattern matching in template arguments. Will it be fixed a newer C version ?

CodePudding user response:

It's basically the same as with default function arguments: You can only omit parameters from the right. And I don't expect this to change, also because what you want to do can be achieved by adding a layer of indirection:

template<bool DebugMode=false>
struct Wrap {
    template <typename ...T> struct A {};
};

template <typename...T> using A = Wrap<>::A<T...>;

int main() {
    A<double, double> a;
}

Alternatively:

template <bool DebugMode=false,typename ...T>
struct A_impl {};

template <typename...T>
using A = A_impl<false,T...>;

Though here the default false cannot be really used, for the using you still have to specify it.

  • Related