int func(int x){return x;}
...
std::function<int(int)> x = std::bind(func, std::placeholders::_1);
x(123);
- 是否
x(123)
实际上调用operator()
std::function
的仿函数生成它又调用operator()
std::bind
的仿函数生成最终调用func
?这是否被优化为与调用func(123)
一样优化的东西? ? - 仿函数住在哪里
std::bind
产生?在什么范围内?std::bind
如何命名? (会不会有名称冲突) - lambdas 能否替代
std::bind
的所有用法? ? - 是
std::bind
与将其实现为 lambda 一样最佳? std::function
的模板参数的语法怎么了? ?如何对其进行解析以及如何在其他地方使用该模板参数语法?
最佳答案
Does x(123) actually call the operator() of the functor which std::function generated which in turn calls the operator() of the functor which std::bind generated which finally calls func? Does this get optimized into something as optimal as calling func(123)?
我不会将 std::function
的 operator()
描述为“生成的”(它是一个普通成员),但除此之外这是一个很好的描述。优化取决于您的编译器,但请注意,要优化 std::function
的间接寻址(这需要使用类型删除),编译器可能需要执行英雄操作。
Where does the functor live which std::bind generates? In what scope? And how does std::bind name it? (can there be name collisions)
对 std::bind
的调用返回一个未指定类型的仿函数,并且该仿函数的拷贝存储在 x
对象中。此拷贝将与 x
本身一样长。没有涉及名称,所以我不确定你的意思。
Can lambdas replace all uses of std::bind?
没有。考虑 auto bound = std::bind(functor, _1);
其中 functor
是具有重载 operator()
的类型,让我们说long
和 int
。然后 bound(0L)
与 bound(0)
的效果不同,您不能用 lambda 复制它。
Is std::bind as optimal as implementing it as a lambda instead?
这取决于编译器。衡量自己。
What's up with the syntax of the template argument of std::function? How does that get parsed and how can I use that template argument syntax elsewhere?
这是一个函数类型。也许您已经熟悉函数指针/引用的语法:void(*)()
、int(&)(double)
。然后只需从类型中删除指针/引用,您就只有一个函数类型:void()
、int(double)
。您可以像这样使用它们:
typedef int* function_type(long);
function_type* p; // pointer to function
关于c++ - std::bind 和 std::function 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082680/