c++11 - C++ std::mem_fn with overloaded member function -




when compiling following code, visual studio reports:

\main.cpp(21): error c2664: 'std::_call_wrapper<std::_callable_pmd<int classa::* const ,_arg0,false>,false> std::mem_fn<void,classa>(int classa::* const )' : cannot convert argument 1 'overloaded-function' 'int classa::* const '     1>              1>          [     1>              _arg0=classa     1>          ]     1>          context not allow disambiguation of overloaded function 

why compiler confused when creating mem_fptr1? how mem_fptr2 ok when specify types.

can create member function pointer overloaded member function takes no argument?

class classa { public:     void memberfunction()     {         std::cout <<"invoking classa::memberfunction without argument" << std::endl;     }      void memberfunction(int arg)     {         std::cout << "invoking classa::memberfunction integer " << arg << std::endl;     } };  int main() {     auto mem_fptr1 = std::mem_fn<void, classa>(&classa::memberfunction);     auto mem_fptr2 = std::mem_fn<void, classa, int>(&classa::memberfunction);      mem_fptr1(classa());     mem_fptr2(classa(), 3); } 

the template overloads taking variadic list of argument types introduced in c++11 removed in c++14 defect #2048. way specify particular overload specify function type first template argument (the second template argument, class type, can omitted can deduced):

auto mem_fptr1 = std::mem_fn<void()>(&classa::memberfunction); auto mem_fptr2 = std::mem_fn<void(int)>(&classa::memberfunction); 

the function type r composed class type t r t::* give member function type. allows forming std::mem_fn data member (where r non-function type).

note code (for mem_fptr2) not work in c++14 template overloads taking variadic list of argument types removed; above code work in both versions of standard.

an alternative perform member function cast; in case not need specify template arguments mem_fn:

auto mem_fptr1 = std::mem_fn(     static_cast<void (classa::*)()>(&classa::memberfunction)); auto mem_fptr2 = std::mem_fn(     static_cast<void (classa::*)(int)>(&classa::memberfunction)); 




wiki

Comments

Popular posts from this blog

python - Read npy file directly from S3 StreamingBody -

python - Minimize function with Scipy minimize -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -