简体   繁体   English

C++17 默认模板参数:无效使用没有参数列表的模板名称

[英]C++17 Default template arguments: invalid use of template-name without an argument list

With C++17, you can do class template argument deduction in main like in the following example:使用 C++17,您可以在 main 中进行类模板参数推导,如下例所示:

template<class T = int>
struct X{};

int main()
{
    X myX;
}

Why is template argument deduction not allowed for data members?为什么数据成员不允许模板参数推导?

template<class T = int>
struct X{};

struct Y
{
   X myX;
};

int main()
{
   Y myY;
}

error: invalid use of template-name 'X' without an argument list X myX;错误:在没有参数列表 X myX 的情况下无效使用模板名称“X”;

I wasn't involved into the decision, however, I do see some problems in allowing it.我没有参与这个决定,但是,我确实看到允许它存在一些问题。 Let's assume the following code:让我们假设以下代码:

template<class T = int>
struct X
{
    X(T t = T{}) {}
};

This makes your variable still OK:这使您的变量仍然可以:

int main()
{
     Y myY;
}

However, what if Y has a constructor that's implemented in a separate file?但是,如果 Y 有一个在单独文件中实现的构造函数呢?

struct Y
{
    Y();
    X myX{'a'};
};

Y::Y() : myX{0.0} {}

Do we in this case expect myX to be X<int> or X<double> or X<char> ?在这种情况下,我们是否希望myXX<int>X<double>X<char>

I can see that there can be confusion about this.我可以看到对此可能存在混淆。 As the standards commite can't revert it's decisions, it's better to take a small step that's certain and see if people need it and what they expect to happen.由于标准委员会无法恢复其决定,因此最好采取确定的一小步,看看人们是否需要它以及他们期望发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM