C++-如何模板化一个类属性,而不是类的函数

C++ - How to template a class attribute and not the functions of the class?

本文关键字:属性 函数 一个 何模板 C++-      更新时间:2023-10-16

我想为类的一个属性创建模板,但不是所有的函数。

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 templateerror: ‘myClass’ is not a template

如果你需要一个模板数据成员,那么你的类就有作为类模板:

enum myenum { .... };
template <typename T>
class myclass {
 public:
  myenum gettype() const;
  myclass& operator+=(const myclass& rhs);
 private:
  T value_;
};

你的问题不清楚你想要什么,但我猜可能是这样的:

template<typename T>
T getType();

template<typename T>
T myClass::getType()
{
   T t;
   return t;
}

如果你想在你的类中有一个模板化的成员,你必须使类本身成为一个模板。真的没有别的办法了。