根据模板的typename设置private属性

Nat*_* C. 4 c++ templates class

上下文:
我们正在尝试建立一个名为Operand的类模板,它可以将几种类型作为其类型名称T.这些在以下枚举中定义:

enum eOperandType {
    INT8
    INT16,
    INT32,
    FLOAT,
    DOUBLE
};
Run Code Online (Sandbox Code Playgroud)

那些对应于定义的类型<cstdint>,即int8_t, int16_t,等等.

构造函数必须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;
};
Run Code Online (Sandbox Code Playgroud)

接口IOperand在这里并不重要,只是运算符重载的一些原型.

问题:
设置_type属性的最佳方法是什么?最简单的办法是只写几个if/else iftypeid或接近的东西,但我觉得这将是非常脏.此外,我只是认为typeid在模板内部使用只是意味着你在某处做错了什么......对吗?

R S*_*ahu 5

使用辅助类来推导出值_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;
};
Run Code Online (Sandbox Code Playgroud)

等等

并将其用作:

Operand(std::string const & value) : type_(OperandType<T>::t)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

PS

鉴于您可以推断出type_您需要它的任何时间的价值,将它存储为成员变量是否有意义?