【发布时间】:2015-05-12 19:41:48
【问题描述】:
背景:
我们正在尝试设置一个名为 Operand 的类模板,它可以采用多种类型作为其类型名T。这些在以下枚举中定义:
enum eOperandType {
INT8
INT16,
INT32,
FLOAT,
DOUBLE
};
那些对应<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;
};
接口 IOperand 在这里并不重要,只是一些用于运算符重载的原型。
问题:
设置_type 属性的最佳方法是什么?简单的方法是写几个if/else if 和typeid 或类似的东西,但我觉得那样会很脏。此外,我只是认为在模板中使用typeid 只是意味着你在某处做错了......对吗?
【问题讨论】:
-
为什么不将类型
T暴露为typedef? -
为什么不:
template<typename T> class Operand: public IOPerand? -
@TamásSzabó 技术上不一样吗?参看。 stackoverflow.com/a/2024173/4891879