c++ - 是否可以在 C++0x 中使用 auto 执行以下操作?

标签 c++ class c++11 type-inference

Eric Lippert 写了一篇关于 Why no var on fields? 的文章在 C# 中。我很好奇,我们能否在 C++0x 中做到这一点?例如。

struct mystruct_t
{
   auto i = 0, d = 0.0, s = std::string("zero");
};

抱歉,我无法通过最新草稿得出答案。

谢谢,

最佳答案

遗憾的是你不能。该规范在 7.1.6.4/3 中说明并遵循

Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. This use of auto is allowed when declaring variables in a block (6.3), in namespace scope (3.3.6), and in a for-init-statement (6.5.3).

The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).

A program that uses auto in a context not explicitly allowed in this section is ill-formed.

我不确定他们为什么禁止非静态数据成员使用 auto,这会很方便。

关于c++ - 是否可以在 C++0x 中使用 auto 执行以下操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4466433/

相关文章:

c++ - QCalendarWidget 选择颜色

c++ - 为 Qt 应用程序提供 Web 用户界面的最佳方式?

java - 类和类型之间的区别

javascript - 在 anchor 中动态设置类不起作用?

c++ - 在基于 Linux 的远程 HPC 上切换 gcc 版本(无 root 权限)

c++ - Noexcept 对派生类构造函数的 promise : can that be used without promising noexcept on base constructor?

c++ - 可序列化的 Boost 库 header 和仅 header 库

java - 如何从数组类型类中获取元素类型类?

c++ - 为什么不调用构造函数?

c++ - 适用于集合的 std::async 变体