如何将函数引用传递给参数(How to pass function reference into arguments)
我正在使用boost :: function来创建函数引用:
typedef boost::function<void (SomeClass &handle)> Ref; someFunc(Ref &pointer) {/*...*/} void Foo(SomeClass &handle) {/*...*/}将Foo传递给someFunc的最佳方法是什么? 我试过类似的东西:
someFunc(Ref(Foo));I'm using boost::function for making function-references:
typedef boost::function<void (SomeClass &handle)> Ref; someFunc(Ref &pointer) {/*...*/} void Foo(SomeClass &handle) {/*...*/}What is the best way to pass Foo into the someFunc? I tried something like:
someFunc(Ref(Foo));最满意答案
为了将临时对象传递给函数,它必须通过值或常量引用来获取参数。 不允许对临时对象进行非常量引用。 因此,以下任何一项都应该有效:
void someFunc(const Ref&); someFunc(Ref(Foo)); // OK, constant reference to temporary void someFunc(Ref); someFunc(Ref(Foo)); // OK, copy of temporary void someFunc(Ref&); someFunc(Ref(Foo)); // Invalid, non-constant reference to temporary Ref ref(Foo); someFunc(ref); // OK, non-constant reference to named object顺便说一下,当它既不是引用也不是指针时调用类型Ref和实例指针可能有点令人困惑。
In order to pass a temporary object to the function, it must take the argument either by value or by constant reference. Non-constant references to temporary objects aren't allowed. So either of the following should work:
void someFunc(const Ref&); someFunc(Ref(Foo)); // OK, constant reference to temporary void someFunc(Ref); someFunc(Ref(Foo)); // OK, copy of temporary void someFunc(Ref&); someFunc(Ref(Foo)); // Invalid, non-constant reference to temporary Ref ref(Foo); someFunc(ref); // OK, non-constant reference to named objectBy the way, calling the type Ref and the instance pointer when it's neither a reference nor a pointer could be a bit confusing.
更多推荐
发布评论