我有一个模板化类 MyClass
,我想针对各种参数运行它以测量某些值。我知道编译前的确切参数,因此我认为必须有一种方法可以实现目标。
到目前为止我的代码:
template <int T>
class MyClass { /*...*/ };
constexpr int PARAMS[] = {1,2,3 /*, ...*/};
for (constexpr auto& t: PARAMS) {
MyClass<t> myClass;
// ... do sth
}
但是编译器(gcc v4.9.2,C++11)不接受。我还尝试使用 const
而不是 constexpr
,但效果不佳。
这样的事情有可能吗?我真的根本不想使用宏。
最佳答案
#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{};
}
关于c++ - 如何将 constexpr 作为模板参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120290/