Sign in to follow this  
chairthrower

c++ overloading member functions and templates

Recommended Posts

chairthrower    440
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
visitor    643
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this