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

标签 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 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/

相关文章:

java - 如何在 jar 文件中获取类的名称?

Java继承实例化

c++ - 使用别名模板和继承的显式析构函数调用

javascript - 如何在 Vue js x-template 上的 html 属性中解析字符串?

c++ - 引用作为参数的模板参数推导

c++ - 在声明后使用方法扩展类功能

c++ - 了解 C++ 中指针的 const 正确性

c++ - 矩阵 vector 乘法与 Eigen 系数乘积的结合

javascript - 在 Javascript ES6 类中调用方法时出现意外行为

spring - spring DAOSupport有什么优势