C++ std::mem_fn with overloaded member function

前端 未结 1 1476
情歌与酒
情歌与酒 2020-12-17 21:26

When compiling the following code, Visual Studio reports:

\\main.cpp(21): error C2664: \'std::_Call_wrapper

        
相关标签:
1条回答
  • 2020-12-17 22:04

    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));
    
    0 讨论(0)
提交回复
热议问题