c++ - std::bind 和 std::function 问题

标签 c++ c++11

int func(int x){return x;}
...
std::function<int(int)> x = std::bind(func, std::placeholders::_1);
x(123);
  1. 是否x(123)实际上调用operator() std::function 的仿函数生成它又调用 operator() std::bind 的仿函数生成最终调用func ?这是否被优化为与调用 func(123) 一样优化的东西? ?
  2. 仿函数住在哪里 std::bind产生?在什么范围内? std::bind如何命名? (会不会有名称冲突)
  3. lambdas 能否替代 std::bind 的所有用法? ?
  4. std::bind与将其实现为 lambda 一样最佳?
  5. 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::functionoperator() 描述为“生成的”(它是一个普通成员),但除此之外这是一个很好的描述。优化取决于您的编译器,但请注意,要优化 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() 的类型,让我们说longint。然后 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/

相关文章:

c++ - 如何在没有 Singleton 的情况下实现方便的日志记录?

c++ - 从其参数之一找到 vector 中的元素

c++ - 名称查找 - 运算符>>未找到

c++ - 将 C 程序的值发布到网页

c++ - 将模板特化放在一起

c++ - 在 python 中使用链接库中的方法时出现属性错误

c++ - 从容器中获取元素的常量资格的通用方法

c++ - 将参数作为右值引用传递给函数与 const 左值引用

c++ - 模板类中的静态成员初始化

c++ - 打印关键点描述符矩阵 opencv 的值