C++-如何模板化一个类属性,而不是类的函数
C++ - How to template a class attribute and not the functions of the class?
我想为类的一个属性创建模板,但不是所有的函数。
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_;
};
你的问题不清楚你想要什么,但我猜可能是这样的:
template<typename T>
T getType();
template<typename T>
T myClass::getType()
{
T t;
return t;
}
如果你想在你的类中有一个模板化的成员,你必须使类本身成为一个模板。真的没有别的办法了。
相关文章:
- 主函数参数的属性
- C++调用具有 *this 属性的单个帮助程序函数
- 使用 CTRP 时,是否访问访问父构造函数 UB 中的子属性?
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 如何在不知道属性具有哪些构造函数的情况下初始化属性?
- C++ 类/结构中的函数依赖属性
- C++ 中常量属性的初始化构造函数错误
- 在构造函数 c++ 中初始化属性时出现问题
- 静态类属性,C++中的多个构造函数
- 使用智能指针属性创建资源库函数?
- 模板化虚拟函数,管理单个类的不同类属性
- 使用类属性调用具有非类型模板参数的模板函数
- 设置使用 Cereal 序列化库时可以在序列化函数中访问的属性
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 为什么我的函数不改变对象的属性
- 使用setW()函数保存文件时,如何获取每个属性的值
- 获取文件属性函数
- 访问子类的属性/函数