将继承的方法传递给另一个方法
Passing an inherited method to another method
我正在尝试构建一个类,该类具有一个以方法为参数的成员函数。方法是在继承的类中定义的。我构建了一个最小的例子:
#include <iostream>
struct base
{
base() {}
int number(int (*f)(int))
{
return f(1);
}
};
struct option1 : base
{
int timesTwo(int i){return 2*i;}
option1()
{
std::cout << number(timesTwo);
}
};
struct option2 : base
{
int timesThree(int i){return 3*i;}
int timesFour (int i){return 4*i;}
option2()
{
std::cout << number(timesThree);
}
};
int main()
{
option1 a; //I would expect this to print "2"
}
函数number
中的当前语法适用于通用函数,但我无法使它适用于任何继承类的方法。
这里的问题是,您正在传递一个指向成员函数的指针,这与指向非成员函数的指针完全不同(number
函数将其作为参数)。
您可以使用std::function
和std::bind
:
int number(std::function<int(int)> f)
{
return f(1);
}
...
number(std::bind(&option1::timesTwo, this, _1));
您还可以使用模板和额外的参数,如
template<typename T>
int number(T* object, int(T::*f)(int))
{
return (object->*f)(1);
}
...
number(this, &option1::timesTwo);
或者简单的(但并不总是正确的,取决于情况和用例):使回调函数static
:
static int timesTwo(int i){return 2*i;}
我的建议是,您应该使用std::function
来查看解决方案,因为这样就可以很容易地使用任何类型的可调用对象来调用number
函数,比如lambda:
number([](int x){ return x * 2; });
给定的错误显示:
错误:必须调用对非静态成员函数的引用
您可以在方法成员之前添加static
。
我建议您使用std::function
而不是指针函数。
工作代码:
#include <iostream>
#include <functional>
struct base
{
base() {}
int number(std::function<int(int)> f)
{
return f(1);
}
};
struct option1 : base
{
static int timesTwo(int i){return 2*i;}
option1()
{
std::cout << number(timesTwo);
}
};
struct option2 : base
{
static int timesThree(int i){return 3*i;}
static int timesFour (int i){return 4*i;}
option2()
{
std::cout << number(timesThree);
}
};
int main()
{
option1 a; // now it works
}
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 检查哪个对象调用了另一个对象的对象方法
- 不能将方法返回的值用于另一个方法
- Qt将信号与另一个类方法连接
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将一个类的方法指针存储到另一个类中
- 从另一个标头中的标头调用静态方法
- 无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 如果类"A"具有指向另一个类的指针,则"B" A 可以访问 B 类公共方法
- 如何在另一个类中使用类成员的正确方法?
- 重写另一个方法 [C++] 使用的超类回调函数
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 覆盖作为另一个类的好友的虚拟受保护方法
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 返回一个引用C++中另一个类对象的对象的有效方法