Pergunta

Is there any possible way to use variables as template argument? I have to create class with numeral system from 2 to 36. This is my class:

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();
};

I tried to use const tab with the numbers..

    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;

And I get: Error 1 error C2975: 'base_temp' : invalid template argument for 'Klasa_nk5', expected compile-time constant expression

Foi útil?

Solução

Templates are compile-time constructs. If you really need to do it for performance reasons. Then you will need to implement a switch on the variable:

    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;
        ...

Also in C++11, you should be able to make some generic construct like,

    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;
            ...
        }
   } 

which can then be used as,

    mapToTemplate([/* caputures */](/*Whatever data needs to be passed on*/){
        ...
        }, ...);

On top of that it should be possible to reduce the typing required for individual cases using BOOST_PP_REPEAT from boost preprocessor library.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top