如何将函数引用传递给参数(How to pass function reference into arguments)

编程入门 行业动态 更新时间:2024-10-27 12:41:33
如何将函数引用传递给参数(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 object

By the way, calling the type Ref and the instance pointer when it's neither a reference nor a pointer could be a bit confusing.

更多推荐

本文发布于:2023-08-03 03:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1383127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   函数   参数   pass   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!