Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template argument deduction for constructors [duplicate]

Does C++0x have (or was C++0x at some point in time going to have) template argument deduction for constructors? In An Overview of the Coming C++ (C++0x) Standard, I saw the following lines:

std::lock_guard l(m);   // at 7:00

std::thread t(f);       // at 9:00

Does this mean that delegating make_foo function templates are finally redundant?

like image 758
fredoverflow Avatar asked Aug 07 '11 09:08

fredoverflow


People also ask

What is template argument 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.

Can constructors be templated?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely.

Can there be more than one arguments to templates?

Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.

Can we pass Nontype parameters to templates?

Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.


1 Answers

Template argument deduction works for any function, including the constructor. But you can't deduce the class template parameters from arguments passed to the constructor. And no, you can't do it in C++0x either.

struct X
{
    template <class T> X(T x) {}
};

template <class T>
struct Y
{
    Y(T y) {} 
};

int main()
{
   X x(3); //T is deduced to be int. OK in C++03 and C++0x; 
   Y y(3); //compiler error: missing template argument list. Error in 03 and 0x
}

lock_guard and thread aren't class templates. They have constructor templates though.

like image 129
Armen Tsirunyan Avatar answered Oct 23 '22 00:10

Armen Tsirunyan