C++ 静态constexpr在类中初始化:为什么这些示例的行为不同?
我试图编译以下代码,但失败了C++ 静态constexpr在类中初始化:为什么这些示例的行为不同?,c++,constexpr,C++,Constexpr,我试图编译以下代码,但失败了 #include <iostream> #include <vector> struct Foo { static constexpr int A = 10; static constexpr int B = 10; std::vector<int> dat; Foo() : dat(A, B) {} }; int main() { Foo foo; } 奇怪的是,可以编译以下代码: #include
#include <iostream>
#include <vector>
struct Foo {
static constexpr int A = 10;
static constexpr int B = 10;
std::vector<int> dat;
Foo() : dat(A, B) {}
};
int main() {
Foo foo;
}
奇怪的是,可以编译以下代码:
#include <iostream>
#include <vector>
struct Foo {
static constexpr int A = 10;
std::vector<int> dat;
Foo() : dat(A, 10) {}
};
int main() {
Foo foo;
}
#包括
#包括
结构Foo{
静态constexpr int A=10;
std::矢量dat;
Foo():dat(A,10){}
};
int main(){
富富,;
}
为什么第二个参数不能接收constexpr值 因为按值获取size参数,按常量引用获取默认值。至于为什么在第一种情况下需要
B
的定义,您可以检查。由dat(a,B)
odr选择的构造函数使用第二个参数(因为它绑定到引用)。第一个参数未使用odr(因为它是按值传递的)。
#include <iostream>
#include <vector>
struct Foo {
static constexpr int A = 10;
std::vector<int> dat;
Foo() : dat(A, 10) {}
};
int main() {
Foo foo;
}