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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With