Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating member function template specialization in C++

Tags:

c++

templates

I am writing a class in which I want to create member function template specialization like this

namespace aha
{
class Foo
{
public:
    template < typename T >
    T To() const
    {
        // some code here
    }
};
template <>
bool Foo::To < bool > () const
{
    // some other code here
}
}

gcc is giving the error:

Explicit instantiation of 'To < bool >' after instantiation

I would like to do it with template specialization of member functions only so that the users of my library would get the same function while converting Foo to different datatypes like

Foo obj;
bool b( obj.To < std::string > () );
int i( obj.To < int > () );
float f( obj.To < float > () );

and so on.

Please let me know what I am doing wrong in the code.

like image 811
Saurabh Sinha Avatar asked Nov 13 '22 17:11

Saurabh Sinha


1 Answers

Explicit instantiation of 'To < bool >' after instantiation

The above says it all: it gets specialized after the generic version of it has already been used.

Function template specialization can be simulated with overloading, which is a more flexible mechanism (for example, there is no partial specialization for function templates, yet one can achieve the desired effect with overloading):

template<class T> struct Type {}; // similar to boost::type<>

class Foo
{
    template<class T>
    T doTo(Type<T>) const; // the generic version

    bool doTo(Type<bool>) const; // an overload for bool only
    // add more overloads as you please

public:
    template < typename T >
    T To() const {
        return this->doTo(Type<T>());
    }
};
like image 195
Maxim Egorushkin Avatar answered Nov 15 '22 05:11

Maxim Egorushkin