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

C++: Passing a non moveable functor to a 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)...);
  };
}

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

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