如何将函数引用传递给参数

时间:2010-06-01 16:42:34

标签: c++ function boost reference

我正在使用boost :: function来创建函数引用:

typedef boost::function<void (SomeClass &handle)> Ref;
someFunc(Ref &pointer) {/*...*/}

void Foo(SomeClass &handle) {/*...*/}

Foo 传递到 someFunc 的最佳方式是什么? 我试过像:

someFunc(Ref(Foo));

1 个答案:

答案 0 :(得分:5)

为了将临时对象传递给函数,它必须通过值或常量引用来获取参数。不允许对临时对象进行非常量引用。因此,以下任何一种都应该有效:

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和实例pointer可能会有点令人困惑。

相关问题