可以在类数据成员中使用模板参数推导吗? [英] Can template parameter deduction be used in class data members?

查看:262
本文介绍了可以在类数据成员中使用模板参数推导吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 17引入了模板参数演绎

C++17 introduces template argument deduction.

使用gcc-7.2,我可以在函数中轻松使用它:

With gcc-7.2, I can use it easily in a function:

int test() {
  std::pair d(0, 0.0);
}

我期望这种相同的语法可以在类非静态数据成员中工作,例如:

I was expecting this same syntax to work in class non-static data members, like:

class Test {
  std::pair d_{0, 0.0};
};

但是这会导致gcc 错误:无效使用模板名称...没有参数列表,其中 - std = c ++ 17 已通过。

but this causes gcc error: invalid use of template-name ... without an argument list, with --std=c++17 passed.

我尝试了一些其他的组合,但没有一个可以工作。

I tried a few other combinations, but none seems to work.

这是标准预期的行为,还是编译器不完全支持的情况?我无法在标准中找到对类数据成员的明确引用。

Is this the intended behavior by the standard, or is this a case of incomplete support by the compiler? I can't find any explicit reference to class data members in the standard.

我的用例当然要复杂得多,因为这个语法非常方便函数被传递并存储)。

My use case is of course much more complex, having this syntax would be extremely convenient (think functions being passed and stored).

推荐答案


这是标准的预期行为,还是这是编译器不完全支持的情况吗?

是的,这是预期的行为。 [dcl.type.class.deduct] 的内容如下:

Yes, this is intended behavior. [dcl.type.class.deduct] reads:


如果推导类类型的占位符在 decl说明符中显示为 decl-说明符初始化声明([dcl.init])的一个变量,[...]

If a placeholder for a deduced class type appears as a decl-specifier in the decl-specifier-seq of an initializing declaration ([dcl.init]) of a variable, [...]

占位符对于推导出来的类类型,也可以用在的new-type-id type-id type-specifier-seq new-expression ,或者在显式类型转换(功能符号)中作为简单类型说明符推导类类型的占位符不应出​​现在任何其他上下文中

A placeholder for a deduced class type can also be used in the type-specifier-seq in the new-type-id or type-id of a new-expression, or as the simple-type-specifier in an explicit type conversion (functional notation). A placeholder for a deduced class type shall not appear in any other context.

非静态数据member不是一个变量,我们也没有其他的情况。

A non-static data member is not a variable, and we're in none of the other situations.

请注意,对于尝试声明的非静态数据成员,同样的原则是正确的 auto

Note that the same principle is true for non-static data members attempting to be declared with auto:

struct X {
    auto y = 0; // error
};

默认成员初始值设定项就是 - 默认初始值设定项。如果你提供了一个用不同类型的表达式初始化成员的构造函数呢?

The default member initializer is just that - a default initializer. What if you provided a constructor that initialized the member with expression(s) of different types?

这篇关于可以在类数据成员中使用模板参数推导吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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