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.

petrbel
  • 2,428
  • 5
  • 29
  • 49

1 Answers1

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

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160