c++ - 如何将类的非静态方法传递给类的数据成员的构造函数
问题描述
我有一个C
方法类func
。C
还有一个数据成员m_func_taker
,其构造函数接受一个std::function
参数。我怎样才能C::func
传入m_func_taker
's 的构造函数?
我有一些示例代码(单击此处运行):
#include <iostream>
#include <functional>
template<typename out_t, typename in_t>
struct my_type{
using F = std::function<out_t(in_t)>;
F m_f;
my_type(F f) : m_f(f) {}
};
class C{
public:
my_type<double,double> m_func_taker;
double func(double in) {
return 2*in;
}
C() : m_func_taker(func) {}
};
int main() {
// your code goes here
return 0;
}
我收到以下错误:“prog.cpp:19:25:错误:无效使用非静态成员函数 'double C::func(double)' C() : m_func_taker(func) {}”
static
当我将方法更改为并更改时,它编译得很好
C() : m_func_taker(C::func) {}
但我不能在我的真实程序中做到这一点。
解决方案
您可以将对该方法的调用包装在 lambda 中:
C() : m_func_taker([this](auto d) { return this->func(d); }) {}
这是一个演示。
要从类的方法构造 a std::function
,您可以使用std::bind
:
using std::placeholders::_1;
C() : m_func_taker(std::bind(&C::func, this, _1)) {}
这是一个演示。
从 c++20 开始,您可以通过以下方式简化std::bind_front
:
C() : m_func_taker(std::bind_front(&C::func, this)) {}
这是一个演示。
推荐阅读
- python - Kivy 返回空白屏幕
- windows - Windows 可执行文件的 Data Directory 条目和 Section Header 条目之间有什么区别?
- c# - 在 c# 中使用 vsphere-automation-sdk.net 从 VMWare 禁用 VM 的网络接口卡中的问题
- c# - 未检查系统 IP 地址,应用程序无法运行
- session - 为什么会话不适合 CORS?
- python - 如何判断我的 python 程序是否向 sys.stdout 写入了任何内容(在同一个程序中)?
- java - 为什么调试报告会在单击微调器时记录“尝试完成输入事件,但输入事件接收器已被释放”?
- java - 如何在布局中包含 listView 以及布局中的其他视图
- reactjs - Antdesign Datepicker 转换为 Typescript
- excel - 列范围 A 到 Z 的最后一个非空单元格