• Advertisement
Sign in to follow this  

c++ overloading member functions and templates

This topic is 3214 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is this example of overloading permitted under the standard ? I have several member functions overloaded on different argument types, as well as a single catch-all type templatized member function. I vaguely know that member specialization is not supported in c++ but I am not sure this properly describes my code. It compiles without warning and behaves as I expect under g++ (it should output "x1,x1,unknown") but I do not currently have a copy of VS (which I want to support) handy to test.
#include <iostream>

struct X1 { };
struct X2 { };
struct X3 { };

struct A
{
    void operator () ( const X1 &x1) { std::cout << "x1\n"; }
    
    void operator () ( const X2 &x2) { std::cout << "x2\n"; }
   
    template< class T>
    void operator () ( const T &p) { std::cout << "unknown\n"; }
};

int main()
{
    A   a;
    a( X1());
    a( X2());
    a( X3());
}

Share this post


Link to post
Share on other sites
Advertisement
It should be correct. In case of overloading, the compiler first looks for exact matches among non-template overloads, and if not found goes on to find the best match among templated overloads (if you have more than one).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement