[英]Member access and template specialization
I have this class template 我有这个类模板
template <typename T>
class Wrapper
{
public:
virtual void parse(std::string s) = 0;
protected:
T value;
};
ideally, each type should know how to parse itself from a string, so I would like to have, for instance, specializations such as 理想情况下,每个类型都应该知道如何从字符串中解析自己,所以我希望有一些特殊化,比如
template<>
class Wrapper<int>
{
public:
virtual void parse(std::string s)
{
value = atoi(s.c_str());
}
};
however, apparently, I can't access the "value" member from the main template. 但是,显然,我无法从主模板访问“value”成员。 What I get is something like: 我得到的是:
In member function 'virtual void Wrapper<int>::parse(std::string)':
error: 'value' is not a member of 'Wrapper<int>'
adding this->
in front of value
doesn't help. 在value
面前添加this->
无济于事。
Do you have any idea how to fix this? 你知道如何解决这个问题吗?
Thanks 谢谢
The various specializations of class template are completely unrelated to each other. 类模板的各种特化完全不相互关联。 Wrapper<int>
does not know anything about eg Wrapper<char>
. Wrapper<int>
对Wrapper<char>
一无所知。 So you need to separately define the data members for each specialization 因此,您需要为每个专业化单独定义数据成员
template<>
class Wrapper<int>
{
public:
virtual void parse(std::string s)
{
value = atoi(s.c_str());
}
protected:
int value;
};
There is also the question of the virtual
keyword in front of parse()
. 在parse()
还存在virtual
关键字的问题。 You do not need it here unless you intend Wrapper<int>
to be a base class that can have its parse()
method redefine by subsequent derived classes. 除非您希望Wrapper<int>
成为可以让后续派生类重新定义其parse()
方法的基类,否则此处不需要它。 If all you are going to do is create various Wrapper<>
specializations, then you should not make parse()
virtual. 如果您要做的只是创建各种Wrapper<>
,那么您不应该使parse()
虚拟。
I think I solved it, the trick is to specialize only the member functions, not the whole class 我想我解决了它,诀窍是只专注于成员函数,而不是整个类
template<>
void Wrapper<int>::parse(std::string s)
{
this->value = atoi(s.c_str());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.