C++ 定义静态constexpr自动类变量

C++ 定义静态constexpr自动类变量,c++,c++11,language-lawyer,c++14,auto,C++,C++11,Language Lawyer,C++14,Auto,由于引用未定义,以下代码无法链接: // file.h struct S { static constexpr auto x = 0; }; // file.cpp int main() { auto const & ref = S::x; } 根据的建议,这似乎适用于clang 3.5: // file.h struct S { static constexpr auto x = 0; }; // file.cpp constexpr decltype(S

由于引用未定义,以下代码无法链接:

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

// file.cpp
int main() {
    auto const & ref = S::x;
}
根据的建议,这似乎适用于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;
}

它实际上是有效的C++吗?这似乎违反了函数遵循的“处处自动或无处自动”规则(您可以向前声明返回自动的函数,然后将其定义为返回自动,但不能将自动与非自动混合使用)。类型说明符有两个相关但不同的用途

[dcl.spec.auto]/1

auto
decltype(auto)
类型说明符用于 指定一个占位符类型,该占位符类型稍后将被替换为 来自初始值设定项。
auto
类型说明符也用于 引入具有尾部返回类型的函数类型,或 表示lambda是通用lambda

对于静态成员,类型由初始值设定项确定,因此
x
在其声明的末尾已经有了类型
int

[dcl.spec.auto]/4

使用
auto
decltype(auto)
声明的变量类型为 从它的初始值推导而来

您提到的规则仅适用于函数和函数模板,与声明变量时使用
auto
无关

[dcl.spec.auto]/13

函数或函数模板的重新声明或专门化 使用占位符类型的声明返回类型也应 使用该占位符,而不是推断类型


我不确定问题是什么,
x
的类型在其声明完成后即为
int
。我在这段代码中担心的是,至少在C++11中,它可能推断出一种类型的std::initializer\u list而不是int?