9

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?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • 1
    Oh wait, I think I confused constructors of class templates with constructor templates of classes... still an interesting question, methinks. – fredoverflow Aug 07 '11 at 09:36

1 Answers1

16

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.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 3
    Your post was in 2011, but to update a bit the C++1y should have it soon : http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3836.html look at paper N3602 on the page (http://open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3602.html). – daminetreg Mar 21 '14 at 10:34