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.
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>());
}
};
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