C++ C++;-如何模板化类属性而不是类的函数?
我想模板化一个类的属性,但不是所有的函数C++ C++;-如何模板化类属性而不是类的函数?,c++,class,templates,C++,Class,Templates,我想模板化一个类的属性,但不是所有的函数 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
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
。我想知道如何在不模板化所有类的情况下模板化属性T\u值
如果我尝试对属性执行相同的操作,我的意思是:
template<typename T>
T _value;
模板
T_值;
我有一个错误:
错误:数据成员“\u值”不能是成员模板
错误:“myClass”不是一个模板
您的问题不清楚您想要什么,但我猜可能是这样的:
template<typename T>
T getType();
template<typename T>
T myClass::getType()
{
T t;
return t;
}
模板
T getType();
模板
T myClass::getType()
{
T;
返回t;
}
如果你想在你的类中有一个模板成员,你必须使类本身成为一个模板。真的没有别的办法了 如果需要模板数据成员,则类必须是类模板:
enum myenum { .... };
template <typename T>
class myclass {
public:
myenum gettype() const;
myclass& operator+=(const myclass& rhs);
private:
T value_;
};
enum myenum{….};
模板
类myclass{
公众:
myenum gettype()常量;
myclass和运算符+=(常量myclass和rhs);
私人:
T值;
};
为什么投票被否决?当然,这可以说得更清楚,但其他人仍然可以从中受益。没有枚举类型,我不是在这里写的,但我需要对它进行模板化。事实上,为了了解类型,我会将枚举添加到我的帖子中。@ellayer,enum
与模板化有什么关系?您想有许多不同的枚举类型吗?这只是一个示例。我不想模板化整个类,因为我不想模板化该类的所有函数。但是我不知道怎么做,因为我有一个模板属性,它要求类被模板化。或者我不知道怎么做,这就是我为什么问的原因。@Elfayer正如我在回答中所说,你的类必须是一个模板。这是没有办法的。那么我能为操作符+
功能做些什么呢?不管怎样,我还是要通过打字?