c++ - 如何将 constexpr 作为模板参数传递?

标签 c++ templates c++11 constexpr

我有一个模板化类 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{};
}

DEMO

关于c++ - 如何将 constexpr 作为模板参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120290/

相关文章:

c++ - boost 链接错误 LNK2038 : “boost_log_abi” “v2s_mt_nt6” doesn't match “v2_mt_nt6"

c++ - 将使用 CMake 的大型 C++ 项目编译为 WebAssembly

c++ - 类型删除和分配器 : what's the expected behavior?

c++ - g++ 不能静态链接 libmongcxx(r3.0.2) 但动态链接有效

C++11 lambda 捕获列表 [=] 使用引用

c++ - 这两个函数调用在内存管理方面的差异?

c++ - 了解使用 GCC 时编译时间花在哪里

c++ - 可变参数模板未在 MSVC 中编译?

c++ - 无法将空的初始值设定项分配给 unique_ptrs 的 vector

c++ - 避免代码重复(常量正确性)redux