C ++ 17默认模板参数:没有参数列表的模板名称的无效使用 [英] C++17 Default template arguments: invalid use of template-name without an argument list

查看:84
本文介绍了C ++ 17默认模板参数:没有参数列表的模板名称的无效使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 17,您可以像下面的示例一样在main中进行类模板参数推导:

With C++17, you can do class template argument deduction in main like in the following example:

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;
}

错误:在没有参数列表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;
}

但是,如果Y具有在单独的文件中实现的构造函数怎么办?

However, what if Y has a constructor that's implemented in a separate file?

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

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

在这种情况下,我们是否期望 myX X< int> X< double> X< char>?

Do we in this case expect myX to be X<int> or X<double> or 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.

这篇关于C ++ 17默认模板参数:没有参数列表的模板名称的无效使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆