定义 static constexpr auto class 变量
Defining static constexpr auto class variable
由于未定义的引用,以下代码无法 link:
// file.h
struct S {
static constexpr auto x = 0;
};
// file.cpp
int main() {
auto const & ref = S::x;
}
根据 Why doesn't the C++11 'auto' keyword work for static members? 的建议,这似乎适用于 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++ 吗?这似乎违反了函数遵循的 "auto everywhere or nowhere" 规则(您可以转发声明一个 returns auto 的函数,然后将其定义为 return auto,但您不能将 auto 与非 -汽车)。
auto
类型说明符有两个相关但独立的目的
[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.
对于您的静态成员,类型由初始化程序确定,因此 x
在其声明末尾已经具有类型 int
。
[dcl.spec.auto] / 4
The type of a variable declared using auto
or decltype(auto)
is
deduced from its initializer.
您提到的规则仅适用于函数和函数模板,与声明变量时auto
的使用无关。
[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.
由于未定义的引用,以下代码无法 link:
// file.h
struct S {
static constexpr auto x = 0;
};
// file.cpp
int main() {
auto const & ref = S::x;
}
根据 Why doesn't the C++11 'auto' keyword work for static members? 的建议,这似乎适用于 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++ 吗?这似乎违反了函数遵循的 "auto everywhere or nowhere" 规则(您可以转发声明一个 returns auto 的函数,然后将其定义为 return auto,但您不能将 auto 与非 -汽车)。
auto
类型说明符有两个相关但独立的目的
[dcl.spec.auto] / 1
The
auto
anddecltype(auto)
type-specifiers are used to designate a placeholder type that will be replaced later by deduction from an initializer. Theauto
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.
对于您的静态成员,类型由初始化程序确定,因此 x
在其声明末尾已经具有类型 int
。
[dcl.spec.auto] / 4
The type of a variable declared using
auto
ordecltype(auto)
is deduced from its initializer.
您提到的规则仅适用于函数和函数模板,与声明变量时auto
的使用无关。
[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.