Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set private attribute depending on template's typename

Context:
We're trying to set up a class template, named Operand, which could take several types as its typename T. Those are defined in the following enum:

enum eOperandType {
    INT8
    INT16,
    INT32,
    FLOAT,
    DOUBLE
};

Those correspond to the types defined in <cstdint>, that is, int8_t, int16_t, and so on.

The constructor must be Operand(std::string const & value);.

template<class T>
class Operand : public IOperand
{

public:
    Operand(std::string const & value)
    {
        std::stringstream ss(value);

        ss >> _value;
        //_type = ??? ;
    }

[...]

private:
    Operand(void){}

    eOperandType    _type;
    T               _value;
};

The interface IOperand is nothing important here, just some prototypes for operator overloads.

Question:
What's the best way to set the _type attribute? The easy way would be to just write several if/else if with typeid or something close to that, but I feel like that would be pretty dirty. Furthermore, I just think that using typeid inside of a template just means that you're doing something wrong somewhere... right?

like image 216
Nathanael C. Avatar asked Jan 09 '23 09:01

Nathanael C.


1 Answers

Use a helper class to deduce the value of _type.

template <typename T> struct OperandType;

template <> struct OperandType<int8_t>
{
    static const eOperandType t = INT8;
};

template <> struct OperandType<int16_t>
{
    static const eOperandType t = INT16;
};

etc.

and use it as:

Operand(std::string const & value) : type_(OperandType<T>::t)
{
   ...
}

PS

Given that you can deduce the value of type_ any time you need it, does it make sense to store it as a member variable?

like image 74
R Sahu Avatar answered Jan 15 '23 16:01

R Sahu