我知道有很多类似的问题,但又有些不同的问题。这是关于以下情况:
#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;
}
据我所理解constexpr
用于编译时常量。因此编译器已经可以进行一些计算,例如计算VALUE
。我也可以明显地定义一个constexpr std::array<,>
,我可以从中将值分配给运行时变量。我希望编译器已经设置value = 4
进入可执行程序,以避免加载操作。但是,我无法直接从静态成员分配,出现错误
undefined reference to `MyClass<int>::ARRAY'
clang-3.7: error: linker command failed with exit code 1
这对我来说没有意义,因为它可以通过另一个中间步骤来完成constexpr
多变的。
所以我的问题是:为什么类的 static constexpr 成员不能分配给运行时变量?
注意:在我的MWE中,该类是模板类,这不会影响错误。然而,我最初对这个特殊情况感兴趣,我希望它对于非模板类来说更通用。
(编译器是clang++
or g++
with -std=c++11
- 他们给出了同样的错误)
编辑:@Bryan Chen:忘记了输出行。现在已添加。