Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do the following with auto in C++0x?

Eric Lippert has written an article about Why no var on fields? in C#. I was curious, will we be able to do that in C++0x? ex.

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

I couldn't reach an answer through the latest draft, sorry.

Thanks,

like image 309
Khaled Alshaya Avatar asked Dec 16 '10 23:12

Khaled Alshaya


People also ask

When to use auto C?

The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.

What does auto type specifier do?

auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable. Instead, the compiler deduces the type of an auto variable from the type of its initializer expression.

Is using auto good practice C++?

Automatic type deduction is one of the most important and widely used features in modern C++. The new C++ standards have made it possible to use auto as a placeholder for types in various contexts and let the compiler deduce the actual type.

How to initialize auto variable in C++?

You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.


1 Answers

Sadly you cannot. The spec says at 7.1.6.4/3 and follows

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.

I'm not sure why they forbid auto for non-static data members, it would be quite handy.

like image 162
Johannes Schaub - litb Avatar answered Sep 29 '22 04:09

Johannes Schaub - litb