1

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.

9
  • Please provide a minimal reproducible example. Can't repro (once I add the missing int in arr and ; for foo) Commented May 24, 2016 at 20:34
  • @Barry Fairly sure that you will run into ODR issues once you do a dimension call with a run-time value. Commented May 24, 2016 at 20:41
  • Not sure I understand the question; two specializations of foo have the same type iff their Args... are the same, so why do you need to do anything beyond std::is_same? Commented May 24, 2016 at 20:42
  • @Barry here you can see a minimal example Commented May 24, 2016 at 20:43
  • Is the question just how to fix that undefined reference? Commented May 24, 2016 at 20:44

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. Thanks a ton for the fix and explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.