Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No deduction in a class template

Tags:

c++

templates

template<typename T> 
class A { 
  public: 
    A(T b) : a(b) { 
    } 
  private: 
    T a; 
}; 

A object(12); //Why does it give an error?

Why can't the type T be deduced from the argument 12 automatically?

like image 717
Shane McMahon Avatar asked Oct 10 '10 11:10

Shane McMahon


People also ask

What is template deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

What is a non type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

What is type deduction c++?

Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.


1 Answers

Template argument deduction applies only to function and member function templates but not to class templates. So your code is ill-formed.

You need to provide the template argument explicitly.

A<int> object(12); //fine
like image 54
Prasoon Saurav Avatar answered Oct 26 '22 05:10

Prasoon Saurav