【问题标题】:C++: Variables as template argumentC++:变量作为模板参数
【发布时间】:2014-06-20 18:50:42
【问题描述】:

有没有可能使用变量作为模板参数的方法?我必须创建数字系统从 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”的模板参数无效,预期的编译时常量表达式

【问题讨论】:

  • 不,你不能这样做。模板是一种编译时构造。
  • 那么,我可以提前为 2 到 36 的数字创建模板吗?然后再使用它们?
  • 真正的问题是:你为什么要使用模板?只需使用普通课程!

标签: c++ templates variables arguments


【解决方案1】:

模板是编译时构造。如果您出于性能原因确实需要这样做。然后你需要在变量上实现一个开关:

    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_REPEAT 应该可以减少个别情况所需的类型。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 2016-11-18
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多