Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 802
tunnuz Avatar asked Sep 19 '13 14:09

tunnuz


People also ask

What is a template specialization?

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.

Can a member function be a template?

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++?

How many types of specialization are there in c++? Explanation: There are two types of specialization. They are full specialization and partial specialization.

Are template specializations inline?

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.


1 Answers

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.

like image 89
TemplateRex Avatar answered Sep 19 '22 18:09

TemplateRex