Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default template parameters: Why does the compiler complain about not specifying template argument?

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.

like image 276
badmaash Avatar asked Jun 27 '12 16:06

badmaash


People also ask

Can we specify default value for template arguments?

Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.

Can default argument be used with the template class?

Can default arguments be used with the template class? Explanation: The template class can use default arguments.

What is a purpose is template parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Which parameter is allowed for non-type template?

The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.


1 Answers

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.

like image 162
Nawaz Avatar answered Oct 02 '22 20:10

Nawaz