C++ std::mem_fn with overloaded member function

◇◆丶佛笑我妖孽 提交于 2019-11-30 20:47:06

The template overloads taking a variadic list of argument types were introduced in C++11 but removed in C++14 as defect #2048. The way to specify a particular overload is to specify a function type as the first template argument (the second template argument, the class type, can be omitted as it can be deduced):

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

The function type R is then composed with the class type T as R T::* to give the member function type. This also allows forming a std::mem_fn to a data member (where R is a non-function type).

Note that your code (for mem_fptr2) does not work in C++14 where the template overloads taking a variadic list of argument types are removed; the above code will work in both versions of the Standard.

An alternative is to perform a member function cast; in this case you do not need to specify template arguments to 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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!