C++:将不可移动的仿函数传递给 std::function

标签 c++ std-function

如何将不可移动的对象传递给 std::function?一个足够简单的替代方法是传递一个 std::reference_wrapper,这将创建函数生命周期依赖于对象的需要。下面的示例代码更好地解释了这个问题。


class Player {
  std::atomic_int runs {0};
  std::string name;

public:
  Player(std::string&& name) : name(std::move(name)) {}  //...
  void inc() { ++runs;}
};

class PlayerStats {
  std::array<std::unique_ptr<Player>,2> players;
public:
  PlayerStats() {
    for(int i = 0; i<2 ; i++)
      players[i] = std::unique_ptr<Player>(new Player{"player"+std::to_string(i)});
  }
  Player* const operator() (int index) const {
    return players[index].get();
  }
};

using player_total_f = std::function<Player* const(int index)>;

class GameStats {
  std::string game;
  std::string date;
  player_total_f f;

public:
  GameStats(std::string&& game, std::string&& date, player_total_f&& _f) :
    game(std::move(game)), date(std::move(date)), f(std::move(_f)) {}
};

int main(int argc, char *argv[])
{
  PlayerStats st;
  //GameStats("game1","10.11",std::ref(st)); //this seems like the only possibility, no way to make GameStats own the functor
  return 0;
}

如何将此处的函数设置为 PlayerStats,因为它是不可复制的,std::ref 似乎是唯一的可能性?

最佳答案

template<class F>
auto shared_function( F&& f ){
  auto spf=std::make_shared<std::decay_f<F>>(std::forward<F>(f));
  return [spf=std::move(spf)](auto&&...args)->decltype(auto){
    return (*pf)(decltype(args)(args)...);
  };
}

在共享指针中拥有它。稍微改变了语义,但修复了它。

或者编写您自己的非复制标准函数。

关于C++:将不可移动的仿函数传递给 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54253863/

相关文章:

C++:如何管理对象生命周期和依赖关系?

c++ - 在 C 和 C++ 中更改控制台输出的背景颜色

c++ - 在c++中使用gsl时如何避免静态成员函数

c++ - 将抽象仿函数分配给 std::function - 为什么 std::ref 是一个解决方案?

c++ - 将函数包装器转换为 std::function

c++ - 错误: No Matching function to call to 'online'

C++ char算术溢出

c++ - 隐藏自定义 QwtSymbol 的边界矩形

c++ - 指向函数和 std::function 的指针:第一个编译而不是第二个?

c++ - 在执行期间重新分配 std::function 对象