Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将constexpr作为模板参数传递?_C++_Templates_C++11_Constexpr - Fatal编程技术网

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

C++ 如何将constexpr作为模板参数传递?,c++,templates,c++11,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; //

我有一个模板类
MyClass
,我想为各种参数运行它,以便测量一些值。我在编译之前就知道了确切的参数,因此我认为一定有办法实现这个目标

到目前为止,我的代码是:

template <int T>
class MyClass { /*...*/ };


constexpr int PARAMS[] = {1,2,3 /*, ...*/};
for (constexpr auto& t: PARAMS) {
    MyClass<t> myClass;
    // ... do sth
}
模板
类MyClass{/*…*/};
constexpr int PARAMS[]={1,2,3/*,…*/};
用于(constexpr auto&t:PARAMS){
MyClass MyClass;
//…做某事
}
但是编译器(gcc v4.9.2,C++11)不接受这一点。我还尝试使用
const
而不是
constepr
,但效果并不理想

有可能这样做吗?我真的根本不想使用宏。

\include
#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{};
}
#包括 constexpr int PARAMS[]={1,2,3,/*…*/}; 模板 空条() { MyClass MyClass; //做某事 } 模板 void foo(std::index_序列) { 使用dummy=int[]; 静态_cast(虚拟{0,(bar(),0)…..}); //(bar(),…);自C++1z以来 } int main() { foo(std::make_index_sequence{}); //自C++1z以来 //对于std::数组参数{}; }

循环在运行时执行,而不是在编译时执行。模板都是在编译时解析的。您需要一个编译时循环(可以通过编译时递归或可变模板参数包扩展来实现)。请改用递归。您能否解释为什么需要
0
?哦,我想我现在明白了。。。这是逗号运算符,我猜…@ChrisBeck 0s将用于填充包扩展后的临时数组(第一个是防止0长度数组错误),
static\u cast
只是为了抑制未使用的变量警告?我猜它一定和我一直看到的
(void)unused\u var
一样…@ChrisBeck是的,它是用来抑制警告的