2

The following code fails to link due to an undefined reference:

// file.h
struct S {
    static constexpr auto x = 0;
};

// file.cpp
int main() {
    auto const & ref = S::x;
}

Following the advice of Why doesn't the C++11 'auto' keyword work for static members?, this seems to work with clang 3.5:

// file.h
struct S {
    static constexpr auto x = 0;
};

// file.cpp
constexpr decltype(S::x) S::x;

int main() {
    auto const & ref = S::x;
}

Is it actually valid C++? This seems to violate the rule of "auto everywhere or nowhere" that functions follow (you can forward declare a function that returns auto and then define it to return auto, but you cannot mix auto with non-auto).

David Stone
  • 26,872
  • 14
  • 68
  • 84

1 Answers1

2

The auto type-specifier serves two related but separate purposes

[dcl.spec.auto] / 1

The auto and decltype(auto) type-specifiers are used to designate a placeholder type that will be replaced later by deduction from an initializer. The auto type-specifier is also used to introduce a function type having a trailing-return-type or to signify that a lambda is a generic lambda.

In the case of your static member, the type is determined by the initializer, so x already has type int at the end of its declaration.

[dcl.spec.auto] / 4

The type of a variable declared using auto or decltype(auto) is deduced from its initializer.

The rule you mention applies to functions and function templates only, and is unrelated to the use of auto when declaring variables.

[dcl.spec.auto] / 13

Redeclarations or specializations of a function or function template with a declared return type that uses a placeholder type shall also use that placeholder, not a deduced type.

user657267
  • 20,568
  • 5
  • 58
  • 77