我想模板化类的属性,但不是所有函数。
enum myEnum
{
CHAR,
INT,
FLOAT,
DOUBLE
};
class myClass
{
public:
myClass(T);
~myClass();
myEnum getType(); // need to template it to know the type
myClass *operator+(const myClass&);
/*
I don't want to template it, because I don't need it,
I can find the type tanks to getType() (for the precision of the operation,
I'll need it, ie. for a char + int)
*/
protected:
T _value;
std::string _sValue;
};
我知道如何在类中模板化一个独特的函数,我只需要写 template<typename T>
位于类中的函数之上。我想知道如何模板化属性 T _value
无需模板化所有类。
如果我尝试对属性执行相同的操作,我的意思是:
template<typename T>
T _value;
我有这样的错误:
error: data member '_value' cannot be a member template
error: ‘myClass’ is not a template
最佳答案
如果您需要模板数据成员,那么您的类必须是类模板:
enum myenum { .... };
template <typename T>
class myclass {
public:
myenum gettype() const;
myclass& operator+=(const myclass& rhs);
private:
T value_;
};
关于C++ - 如何模板化类属性而不是类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919990/