How do I store a vector of std::bind without a specific case for the template?

那年仲夏 提交于 2019-12-04 05:46:08
CinchBlue

So, it appears that this isn't possible--std::bind doesn't appear to have a normally nameable/explicit type--the type is usually generated according to the signature of the bound function, and doesn't appear to be specifiable. Using std::function seems to be the only way to wrap std::bind functions and store them in a vector.

Even for lambdas, this doesn't seem possible--using a wrapper in the form of std::function seems to be the go-to answer, despite the increased size of the resulting function-object.

Possible alternatives might be storing Functor objects designed to mimic closures couples with generic objects with a type-checking layer (though this seems quite heavy). Whatever the case, using std::function seems to be the cleanest solution.

How about this?

#include <iostream>
#include <functional>
#include <vector>

int add(int a, int b) { return a + b; }

using bound_add_t = decltype(std::bind(add, std::placeholders::_1, int()));

int main() {
  std::vector<bound_add_t> vec;
  vec.emplace_back(add,std::placeholders::_1, 1);
  vec.emplace_back(add,std::placeholders::_1, 2);
  vec.emplace_back(add,std::placeholders::_1, 3);

  for (auto &b : vec)
    std::cout << b(5) << std::endl;

  return 0;   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!