Search code examples
c++c++11overloadingampersand

C++ member function overloading with & (ampersand)


How to pick the correct error() member function? Do I need to cast somehow?

using namespace std;

struct test
{
   int error();
   void error(int x);
   int fun();
};

int main() {
   auto f1 = &test::error; // how to pick the correct function?
   auto f2 = &test::fun; // works
}

Solution

  • Do I need to cast somehow?

    Yes, you can use static_cast.

    static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type, as in

    std::for_each(files.begin(), files.end(),
                  static_cast<std::ostream&(*)(std::ostream&)>(std::flush));
    

    So you can:

    auto f1 = static_cast<int(test::*)()>(&test::error);
    auto f2 = static_cast<void(test::*)(int)>(&test::error);