我有代码
void prints_one()
{ cout << "one" << endl; }
int main(int argc, char *argv[])
{
std::function<void()> foo;
foo = prints_one;
foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它按预期工作; 它打印"一".我不知道的是在赋值中调用哪个赋值运算符原型以及如何调用.看看cpp引用,看起来它可能就是这个函数
template <class Fn> function& operator= (Fn&& fn);
Run Code Online (Sandbox Code Playgroud)
但如果那是被调用的原型,我不明白函数如何绑定到右值引用.谢谢!
更新:谢谢大家,我会阅读通用参考资料.关于40两个答案; 此代码打印出它是一个右值引用:
template<class Fn>
class Foo {
public:
Foo() {}
Foo& operator=(Fn&& x)
{
std::cout << std::boolalpha << std::is_rvalue_reference<decltype(x)>::value << std::endl;
}
};
void prints_one()
{
cout << "one" << endl;
}
int main(int argc, char *argv[])
{
Foo<void()> bar;
bar = prints_one;
}
Run Code Online (Sandbox Code Playgroud)
这打印 …