【问题标题】:template argument deduction for constructors [duplicate]构造函数的模板参数推导[重复]
【发布时间】:2011-10-21 18:18:38
【问题描述】:

C++0x 是否有(或者 C++0x 在某个时间点将有)构造函数的模板参数推导?在An Overview of the Coming C++ (C++0x) Standard,我看到了以下几行:

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

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

这是否意味着委托make_foo 函数模板最终是多余的?

【问题讨论】:

  • 哦,等等,我想我将类模板的构造函数与类的构造函数模板混淆了……我认为这仍然是一个有趣的问题。

标签: c++ templates constructor c++11 type-inference


【解决方案1】:

模板参数推导适用于任何函数,包括构造函数。但是你不能从传递给构造函数的参数中推断出类模板参数。不,你不能这样做 C++0x 也是。

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_guardthread 不是类模板。不过他们有构造函数模板。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多