I know there are a lot of similar questions, but somehow different questions. It is about the following situation:
#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;
}
As far as I understand constexpr
is for compile-time constants. So the compiler can do already some calculation, for example to calculate the VALUE
. Also I can obviously define a constexpr std::array<,>
, from which I can assign the values to runtime variables. I would expect the compiler to set already value = 4
into the executable program, to avoid a loading operation. However, I cannot assign directly from the static member, getting the error
undefined reference to `MyClass<int>::ARRAY'
clang-3.7: error: linker command failed with exit code 1
which makes no sense to me, because it can be done with an intermediate step of another constexpr
variable.
So my question is: Why can a static constexpr member of a class not be assigned to a runtime variable?
Note: In my MWE the class is a template class, which does not affect the error. However, I was originally interested in this particular case, which I expect to be more general as for a non-template class.
(Compiler is clang++
or g++
with -std=c++11
- they give the same error)
Edit: @Bryan Chen: Forgot the output lines. Are added now.