C++:变量作为模板参数
C++: Variables as template argument
是否有任何可能的方法将变量用作模板参数?我必须用从2到36的数字系统创建类。这是我的课:
template <unsigned short base_temp>
class Klasa_nk5
{
private:
vector<uint8_t> addition(vector<uint8_t>, vector<uint8_t>);
vector<uint8_t> subtraction(vector<uint8_t>, vector<uint8_t>);
vector<uint8_t> nk5;
static unsigned short base;
public:
Klasa_nk5 operator+ (Klasa_nk5 &);
Klasa_nk5 operator- (Klasa_nk5 &);
template<unsigned short Bbase_temp>
friend ostream& operator<< (ostream&, const Klasa_nk5<Bbase_temp> &);
Klasa_nk5();
Klasa_nk5(vector<uint8_t> & vector_obtained);
Klasa_nk5(int &);
~Klasa_nk5();
};
我试着用const制表符来表示数字。。
int number = 5;
const unsigned short tab[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 };
int base_test_temp;
cout << "Select the base" << endl;
cin >> base_test_temp;
cout << endl;
Klasa_nk5<tab[base_test_temp]>first_nk5(number);
cout << first_nk5 << endl;
我得到:错误1错误C2975:"base_temp":"Klasa_nk5"的模板参数无效,应为编译时常量表达式
模板是编译时构造。如果出于性能原因,您确实需要这样做。然后你需要在变量上实现一个开关:
switch(base)
{
case 1: process<1>(); break;
case 2: process<2>(); break;
case 3: process<3>(); break;
case 4: process<4>(); break;
...
}
...
template<int N>
void process()
{
// Now you can proceed with rest of logic with templatized type
Klasa_nk5<N> klasa_nk5;
...
同样在C++11中,您应该能够制作一些通用构造,如
template<typename Functor, typename... Args>
void mapToTemplate(Functor&& process, Args&& ...args)
{
switch(base)
{
case 1: process<1>(std::forward<Args>(args)...); break;
case 2: process<2>(std::forward<Args>(args)...); break;
...
}
}
然后可以用作
mapToTemplate([/* caputures */](/*Whatever data needs to be passed on*/){
...
}, ...);
除此之外,应该可以使用BOOST预处理器库中的BOOST_PP_REEAT来减少个别情况所需的类型。
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 扩展可变参数模板中的变量名称
- 在类构造函数中定义结构变量的参数
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 存储稍后要转发的变量参数
- C++具有模板成员变量的类. 和参数内存输出
- 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- 为变量模板的每个参数调用模板函数
- 具有推导参数的模板函数指针数组变量
- 函数参数变量总是需要 & 或 * 运算符吗?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 如何在函数中使用非参数变量?
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 基于不断变化的参数/变量的XML get值
- cocos2d-x v3 CallFunc作为参数/变量如何
- 在编译时使用c++元编程中的运行时参数(变量)
- 我可以返回一个非参数变量吗?