简体   繁体   中英

Undefined reference while calling a static constexpr array of variadic types

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM