Ant*_*ier 16 c++ constexpr c++14
我有两个结构a和b:
struct a {
static constexpr int f() {
return 1;
}
static constexpr int c = f();
};
template<int I>
struct b {
static constexpr int f() {
return I;
}
static constexpr int c = f();
};
Run Code Online (Sandbox Code Playgroud)
a显然不起作用,因为f这里没有定义.但为什么地狱b有效呢?
我对此不确定,但我认为编译器将以这种方式扩展该模板(在 int I 为 1 的情况下):
struct b {
static constexpr int f();
static const int c;
};
constexpr int b::f(){
return 1;
};
const int b::c = f();
Run Code Online (Sandbox Code Playgroud)
所以它可以编译,因为 b::f 的调用是在声明之后完成的
事实上,如果你以这种方式声明 a 它将编译:
struct a {
static constexpr int f();
static const int c;
};
constexpr int a::f(){
return 1;
};
const int a::c = f();
Run Code Online (Sandbox Code Playgroud)
所以答案是,在编译过程中,编译器将 b::c 计算为 const 值,而不是 constexpr。
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |