Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the template parameters of a constructor be explicitly specified?

A constructor of a class can be a template function. At the point where such a constructor is called, the compiler usually looks at the arguments given to the constructor and determines the used template parameters from them. Is there also some syntax to specify the template parameters explicitly?

A contrived example:

struct A {    template<typename T>    A() {} }; 

Is there a way to instantiate this class? What is the syntax to explicitly specify the constructor's template parameters?

My use case would be a problem were the compiler doesn't seem to find the correct templated constructor. Explicitly specifying the template parameters would probably generate more useful error messages or even resolve the problem.

like image 288
sth Avatar asked May 18 '10 23:05

sth


People also ask

Can template have default parameters?

You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };

Can you template a constructor?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely. But, the question is asking about "a template constructor with no arguments" If there are no function arguments, no template arguments may be deduced.

Can a template parameter be a function?

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.

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)


Video Answer


1 Answers

No. The C++03 standard says:

[Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.] (§14.5.2/5)

like image 95
James McNellis Avatar answered Sep 30 '22 08:09

James McNellis