Question

I have this code:

struct A{};

template<class T = A>
struct B {
    void foo() {}
};

B b; //Error: missing template arguments before 'b'
     //Error: expected ';' before 'b'
     //More errors
b.foo()

If I make foo() as a template function with the same template 'signature', the compiler doesn't complain about not specifying the template arguments:

struct A {};

struct B {
    template<class T = A>
    void foo() {}
};

B b; //OK
b.foo()

So why do I need to specify an argument for a template class with a default parameter, but not for a template function? Is there some subtlety I am missing?

The reason is because of template argument deduction failure for sure. But I want to know why.

Was it helpful?

Solution

The correct syntax is this (demo):

B<> b; 

The default argument A is assumed for the class template B. The <> part tells the compiler that B is a class template and asks it to take the default parameter as the template argument to it.

OTHER TIPS

The correct syntax, as Nawaz mentions already is:

B<> b;

The reason is that B is the template and B<> is the instantiation of the template with the default argument A. But you need the <> to differentiate when you want an instantiation.

Because you have to say that B is a template:

B<> b;

Even when you don't want to specify any of the arguments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top