今天想探究一下mem_fun_ref的用法。发现,对于无参数或者一个参数的类函数它可以建立引用,但两个或多个参数的函数呢,应该怎么建立引用呢?求高人指点。像下面代码那样,怎么给add函数建立引用呢?
#include <functional>
#include <iostream>
using namespace std;
class Base {
public:
void say() {
cout << "hello" << endl;
}
double pi() {
return 3.1415926;
}
int twice(int x) {
return (2 * x);
}
int add(int x, int y) {
return (x + y);
}
};
int main() {
mem_fun_ref_t<void, Base> handle1 = mem_fun_ref(&Base::say);
mem_fun_ref_t<double, Base> handle2 = mem_fun_ref(&Base::pi);
mem_fun1_ref_t<int, Base, int> handle3 = mem_fun_ref(&Base::twice);
// mem_fun1_ref_t<int, Base, int, int> handle4 = mem_fun_ref(&Base::add);
Base b;
handle1(b);
cout << handle2(b) << endl;
cout << handle3(b, 4) << endl;
// cout << handle4(b, 4, 3) << endl;
return 0;
}
该回答引用ChatGPT
对于多个参数的成员函数,可以使用mem_fun_ref_t的模板参数列表中的第三个参数来指定该函数的参数类型,例如:
mem_fun2_ref_t<int, Base, int, int> handle4 = mem_fun_ref(&Base::add);
这里,mem_fun2_ref_t表示一个有两个参数的成员函数的引用,第一个参数是返回值类型,第二个参数是类类型,第三个和第四个参数分别是成员函数的两个参数类型。因此,上面的语句将创建一个名为handle4的引用,它可以调用Base::add函数,并返回int类型的结果。然后,您可以使用handle4来调用Base对象的add函数,例如:
cout << handle4(b, 4, 3) << endl;
这将输出7,即4和3的和。