Creating a specialized template function in C ++

I am writing a class in which I want to create a member function template specification 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 gives an error:

Explicit instance creation of 'To <bool>' after instance creation

I would like to do this with a specialized member function only so that my library users get the same function when converting Foo to different data types, such as

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

etc.

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

+4
source share
1 answer

Explicit instance creation of 'To <bool>' after instance creation

Everything is said above: it becomes specialized after its general version is already in use.

Function template specialization can be simulated with overloading, which is a more flexible mechanism (for example, there is no partial specialization for function templates, but you can achieve the desired effect when 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>()); } }; 
+2
source

Source: https://habr.com/ru/post/1447523/


All Articles