C ++如何将成员函数传递给函子参数? [英] C++ How do you pass a member function into a functor parameter?
问题描述
我正在使用TRI DDS-这是我要调用的函数的原型:
I am using TRI DDS - here is the prototype for the function I am trying to call:
template<typename T , typename Functor >
dds::sub::cond::ReadCondition::ReadCondition (
const dds::sub::DataReader< T > & reader,
const dds::sub::status::DataState & status,
const Functor & handler
)
所以我有一个看起来像这样的类(省略了无关紧要的内容):
So I have a class that looks a bit like this (with load of irrelevant stuff omitted):
MyClass test{
public:
test(){... mp_reader = ...}; // not complete
start_reader()
{
dds::sub::cond::ReadCondition rc(*mp_reader,
dds::sub::status::DataState::any(),
do_stuff()); // This does not work
}
void do_stuff() {...}
private:
dds::sub::DataReader* mp_reader;
}
所以我只是尝试传入函数do_stuff().我知道这行不通,但是我不确定在什么位置代替const & functor
参数.我可以传递成员函数吗? -如何指定类的实例?
So I just tried to pass in the function do_stuff().. I know this won't work, but I am not sure what to put in here in place of the const & functor
parameter. Can I pass a member function in? - how do I specify the instance of the class?
我尝试在其中放置一个lambda并成功-但是我无法在lambda中访问mp_reader,因为它不在lambda的范围内.但是无论如何,我真的不想使用lambda,而我真的想使用一个函数(因此,最终我可能可以传入一个外部函数).
I tried putting a lambda in there and it worked - but I can't access mp_reader in the lambda because it is not in the scope of the lambda. But anyway I don't really want to use a lambda I really want to use a function (so, eventually I might be able to pass in an external one).
请参阅此处用于RTI DDS功能.这是有关functor
类型的内容:
Please see here for the RTI DDS function. Here is what it says about the functor
type:
"Any type whose instances that can be called with a no-argument function call (i.e. f(), if f is an instance of Functor). Examples are functions, types that override the operator(), and lambdas <<C++11>>. The return type has to be void
"
推荐答案
您可以将lambda函数与捕获一起使用.
You can use a lambda function with a capture.
dds::sub::cond::ReadCondition rc(*mp_reader,
dds::sub::status::DataState::any(),
[this](){ this->do_stuff(); });
这篇关于C ++如何将成员函数传递给函子参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!