C++ C++;17如何保存通用可调用文件以供以后使用
我想保存一个通用的可调用函数及其状态,以供以后使用。请参见下面的示例代码。我可能会使用C++ C++;17如何保存通用可调用文件以供以后使用,c++,generics,stl,c++17,callable,C++,Generics,Stl,C++17,Callable,我想保存一个通用的可调用函数及其状态,以供以后使用。请参见下面的示例代码。我可能会使用std::function或std::bind来实现这一点,但我不知道什么是最好的。另外请注意,在下面示例的main()中,capturedInt必须以可调用状态保存 有哪些可能性: makeCallable(有趣,参数…{…} CallableType 模板 班级服务 { 公众: 模板 服务(Fn&&fun,Args&&Args) { m_callable=makeCallable(有趣,args…);
std::function
或std::bind
来实现这一点,但我不知道什么是最好的。另外请注意,在下面示例的main()
中,capturedInt
必须以可调用状态保存
有哪些可能性:
makeCallable(有趣,参数…{…}
CallableType
s=新服务([capturedInt](){std::cout给定设置,
m_callable
的唯一选项是std::function
。由于functor的类型是构造函数本身的参数,因此必须键入erase functor以保存它以备将来使用,std::function
只是一种机制
因此,m_callable
将是:
std::function<retT ()> m_callable;
我还将使用
std::function
,但将其作为类的接口,如下所示:
template <typename RetT>
class Service
{
public:
Service(std::function<RetT()> fun)
{
m_callable = std::move(fun);
}
Run()
{
m_callable();
}
private:
std::function<RetT()> m_callable;
};
模板
班级服务
{
公众:
服务(标准::功能乐趣)
{
m_callable=std::move(乐趣);
}
运行()
{
m_callable();
}
私人:
std::函数m_可调用;
};
然后,您明确了为类存储可调用项的选项。然后,用户可以决定如何将其参数绑定到可调用项本身,这与std::function是灵活的
s = new Service([capturedInt]() { std::cout << capturedInt << std::endl; } );
s->Run();
s=新服务([capturedInt](){std::cout为什么不使用auto
?虽然我同意std::function是唯一的类型,如果Fn
和Args…
对于一个返回类型可以不同,但是你的m\u callable
的构造并没有利用完美的转发。例如,你不能传递像str::unique\u ptr
这样的纯移动类型。我想实际使用std::bind
,因为完美的转发参数和调用函数以及通过lambda捕获的函数非常重要。但是m_callable=std::bind(std::forward(fun),std::forrward(args)…;
应该可以像对待一样工作。
template <typename RetT>
class Service
{
public:
Service(std::function<RetT()> fun)
{
m_callable = std::move(fun);
}
Run()
{
m_callable();
}
private:
std::function<RetT()> m_callable;
};
s = new Service([capturedInt]() { std::cout << capturedInt << std::endl; } );
s->Run();
struct Foo
{
void MyPrint(int capturedInt) { std::cout << capturedInt << std::endl; }
};
Foo foo;
int capturedInt = 5;
s = new Service(std::bind(&Foo::MyPrint, &foo, capturedInt);
s->Run();