[英]C++ std::mem_fn with overloaded member function
When compiling the following code, Visual Studio reports: 编译以下代码时,Visual Studio报告:
\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 from 'overloaded-function' to 'int ClassA::* const '
1> with
1> [
1> _Arg0=ClassA
1> ]
1> Context does not allow for disambiguation of overloaded function
Why is the compiler confused when creating mem_fptr1
? 创建
mem_fptr1
时,为什么编译器会感到困惑? But some how mem_fptr2
is ok when I specify the types. 但是当我指定类型时,
mem_fptr2
一些方法mem_fptr2
可以。
Can I create member function pointer to an overloaded member function that 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 with 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 a variadic list of argument types were introduced in C++11 but removed in C++14 as defect #2048 . 在C ++ 11中引入了带有可变参量类型列表的模板重载,但在C ++ 14中将其作为缺陷#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 RT::*
to give the member function type. 然后,将函数类型
R
与类类型T
为RT::*
以提供成员函数类型。 This also allows forming a std::mem_fn
to a data member (where R
is a non-function type). 这还允许将
std::mem_fn
形成为数据成员(其中R
是非函数类型)。
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; 请注意,您的代码(对于
mem_fptr2
)在C ++ 14中不起作用,在C ++ 14中,模板重载采用了可变的参数类型列表; 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
: 在这种情况下,您无需为
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.