假设我有一个函数,它需要std::function:
void callFunction(std::function<void()> x)
{
x();
}
Run Code Online (Sandbox Code Playgroud)
我应该x通过const-reference来代替吗?:
void callFunction(const std::function<void()>& x)
{
x();
}
Run Code Online (Sandbox Code Playgroud)
这个问题的答案是否会根据函数的作用而改变?例如,如果它是一个类成员函数或构造函数,它存储或初始化std::function成成员变量.
我试图通过像这样的方法传递一个std :: function:
class dispatch
{
public:
deliver( std::function<void ( void )> task );
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作.但是我希望将参数传递给作为任务提供的一些方法,但是不希望为所有不同的函数<...>形式创建重载.
例如,它只是为了创建一个像下面这样的方法
deliver( std::function& task );
Run Code Online (Sandbox Code Playgroud)
并且只是调用
dispatch->deliver( bind( &Object::method, X ) );
Run Code Online (Sandbox Code Playgroud)
要么
dispatch->deliver( bind( &Object::method, X, arg1, arg2 ) );
Run Code Online (Sandbox Code Playgroud)
等等...
感谢大家的投入.看起来我真正的错误是调用dispatch-> deliver,附加参数也是绑定调用.
dispatch->deliver( bind( &Object::method1, X1, bind( &Object::method1, X2 ) );
Run Code Online (Sandbox Code Playgroud)
错误:/ usr/include/c ++/v1/functional:1539:13:错误:没有匹配函数来调用'__mu_expand'返回__mu_expand(__ ti,__ uj,__ indices());
我正在定义一个这样的类:
class foo {
public:
// I define const and non-const versions of the 'visit' function
// nb. the lambda is passed by reference
virtual void visitWith(std::function<void(foo&)>&);
virtual void visitWith(std::function<void(const foo&)>&) const;
};
Run Code Online (Sandbox Code Playgroud)
foo 可以有孩子,所以我们的想法是递归访问 foo 和所有它的孩子。
当我尝试使用它时,例如。像这样:
foo f;
f.visitWith([&](const foo&) {
// Do something here
});
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误。编译器不知道该怎么做。
我可以通过添加这样的类型转换来使它工作:
foo f;
f.visitWith( (std::function<void(const foo&)>) [&](const foo&) {
// Do something here
});
Run Code Online (Sandbox Code Playgroud)
但这太可怕了。
我怎样才能让它整齐地工作?
编辑:
这可能是 Visual C++ 的问题,它拒绝编译此处给出的代码:
我尝试编译时的 VC++ 输出是:
Edit2:不,Visual C++ 是正确的,代码不明确。请参阅下面的我的解决方案...