Cin*_*lue 6 c++ vector stdbind std-function
在经历了一个问题后std::bind,我想知道是否有可能保留一个vector由std::bind我创建的函数,因此我可以避免使用std::function它和它的重量级包装.
#include <iostream>
#include <functional>
#include <typeinfo>
#include <vector>
int add(int a, int b) {return a + b;}
int main() {
//I believe this here is just a special type of bound function.
auto add2 = std::bind(add, std::placeholders::_1, 2);
auto add3 = std::bind(add, std::placeholders::_1, 3);
//Yup.
std::cout << typeid(add2).name() << std::endl;
//Here's the type of the second function
std::cout << typeid(add3).name() << std::endl;
//Is there a nicer way to do this?
std::vector<decltype(std::bind(add, std::placeholders::_1, 1))> vec;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
虽然可以创建一个std::bind函数向量,但是有一种方法我不必提供绑定函数的特定情况,以便声明一个没有空/假类型的函数的容器std::bind吗?
因此,这似乎是不可能的——std::bind似乎没有通常可命名/显式的类型——该类型通常是根据绑定函数的签名生成的,并且似乎是不可指定的。使用std::function似乎是包装std::bind函数并将其存储在向量中的唯一方法。
即使对于 lambda,这似乎也是不可能的——尽管结果函数对象的大小增加了,但使用 形式的包装器std::function似乎是首选答案。
可能的替代方案可能是存储Functor旨在模仿闭包耦合的对象与具有类型检查层的通用对象(尽管这看起来相当繁重)。无论如何,使用std::function似乎是最干净的解决方案。