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. 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.
Do you have any idea how to fix this?
Thanks
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Member functions can be function templates in several contexts. All functions of class templates are generic but aren't referred to as member templates or member function templates. If these member functions take their own template arguments, they're considered to be member function templates.
How many types of specialization are there in c++? Explanation: There are two types of specialization. They are full specialization and partial specialization.
An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.
The various specializations of class template are completely unrelated to each other. Wrapper<int>
does not know anything about e.g. 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()
. 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. If all you are going to do is create various Wrapper<>
specializations, then you should not make parse()
virtual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With