Reputation: 329
I have the following class
template<int ... Args>
struct foo {
constexpr static int arr[sizeof...(Args)]={Args...};
constexpr int dimension(int i) {return arr[i];}
};
But I get undefined reference to arr
, while calling dimension
. If I move arr
inside the function dimension
then the function cannot be a constexpr
anymore, because it requires two semicolons within the body of the function. For instance, I cannot do
constexpr int a = foo_obj.dimension(2);
My goal is to metaprogrammatically iterate over all the dimensions of a varidic template and compare it to another integral number? Ideally if I have two objects of foo I want to determine if they are equal in every dimension.
Upvotes: 1
Views: 331
Reputation: 303527
Every variable that is odr-used needs a definition. This:
constexpr static int arr[sizeof...(Args)]={Args...};
is a declaration that also initializes arr
, but it isn't a definition. So you just have to provide a definition, which must be both (1) external to the class and (2) still constexpr
. That is:
template<int ... Args>
struct foo {
constexpr static int arr[sizeof...(Args)]={Args...};
constexpr int dimension(int i) const {return arr[i];}
};
template <int... Args>
constexpr int foo<Args...>::arr[sizeof...(Args)];
And now foo<Args...>::arr
is defined.
Upvotes: 6