小编Mih*_*hir的帖子

在将函数分配给std :: function类型时,调用哪个函数原型(以及如何)?

我有代码

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)

这打印 …

c++ c++11 std-function

5
推荐指数
1
解决办法
159
查看次数

标签 统计

c++ ×1

c++11 ×1

std-function ×1