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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With