3

I have a templated class MyClass and I want to run it for various parameters in order to measure some values. I know the exact parameters before the compilation hence I assume there must be a way of achieving the goal.

My code so far:

template <int T> class MyClass { /*...*/ }; constexpr int PARAMS[] = {1,2,3 /*, ...*/}; for (constexpr auto& t: PARAMS) { MyClass<t> myClass; // ... do sth } 

However the compiler (gcc v4.9.2, C++11) doesn't accept that. I also tried using const instead of constexpr which doesn't work as well.

Is it possible to something like this? I really don't want to use macros at all.

3
  • The loop is performed at runtime, not at compile-time. Templates are all resolved at compile-time. Commented Dec 6, 2015 at 17:19
  • 1
    You need a compile-time loop (which can be implemented via compile-time recursion or variadic template parameter pack expansion). Commented Dec 6, 2015 at 17:24
  • use recursion instead Commented Dec 6, 2015 at 17:24

1 Answer 1

6
#include <utility> #include <cstddef> constexpr int PARAMS[] = { 1, 2, 3, /*...*/ }; template <int N> void bar() { MyClass<N> myClass; // do sth } template <std::size_t... Is> void foo(std::index_sequence<Is...>) { using dummy = int[]; static_cast<void>(dummy{ 0, (bar<PARAMS[Is]>(), 0)... }); // (bar<PARAMS[Is]>(), ...); since C++1z } int main() { foo(std::make_index_sequence<sizeof(PARAMS)/sizeof(*PARAMS)>{}); // <std::size(PARAMS)> since C++1z // <PARAMS.size()> for std::array<int,N> PARAMS{}; } 

DEMO

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

4 Comments

Can you explain why the 0's are needed? Oh I think I get it now... that's comma operator in there I guess...
@ChrisBeck the 0s will be used to fill that temporary array after pack expansion (the first one is to prevent a 0-length array error), stackoverflow.com/a/25683817/3953764
static_cast<void> is just to suppress unused variable warning? I guess it must be the same as (void) unused_var like I have always seen...
@ChrisBeck yes, it's to suppress warnings

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.