我想要一个constexpr从constexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.
我第一次写这个(对我来说)明显的方式:
class C1 {
constexpr static int foo(int x) { return x + 1; }
constexpr static int bar = foo(sizeof(int));
};
Run Code Online (Sandbox Code Playgroud)
g++-4.5.3 -std=gnu++0x 对此说:
error: ‘static int C1::foo(int)’ cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
Run Code Online (Sandbox Code Playgroud)
g++-4.6.3 -std=gnu++0x 抱怨:
error: field initializer is not constant
Run Code Online (Sandbox Code Playgroud)
好吧,我想,也许我必须把事情从课堂上移开.所以我尝试了以下方法:
class C2 {
constexpr static int foo(int x) { return x + 1; }
constexpr static int bar;
}; …Run Code Online (Sandbox Code Playgroud) 我知道有很多类似的问题,但不知何故有不同的问题.这是关于以下情况:
#include <iostream>
#include <array>
template<typename T> class MyClass
{
public:
static constexpr std::array<T,4> ARRAY {{4, 3, 1, 5}};
};
int main()
{
constexpr std::array<int, 4> my_array(MyClass<int>::ARRAY); // works fine -> can use the ARRAY to initialize constexpr std::array
constexpr int VALUE = 5*MyClass<int>::ARRAY[0]; // works also fine
int value;
value = my_array[0]; // can assign from constexpr
value = MyClass<int>::ARRAY[0]; // undefined reference to `MyClass<int>::ARRAY
std::cout << VALUE << std::endl;
std::cout << value << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
据我所知 …