为什么在std::protect中没有与std::bind一起使用的C++11
Boost.Bind提供了一个包装其参数的boost::protect助手,这样boost::bind就不会识别和计算它。大多数情况下,std::[c]ref都是一个很好的替代品,只不过它不会以rvalue作为参数。
具体的例子是,考虑以下人为的情况:
#include <type_traits>
#include <functional>
int add(int a, int b)
{ return a + b; }
struct invoke_with_42
{
templa
未指定std::bind的返回类型(有意)。它可以存储在std::function中。
下面的示例程序显示了如何将std::bind()返回的临时对象显式转换为std::函数,以便调用fn1()。
如果返回类型std::bind是可知的,我可以重载回调构造函数&不再需要显式地强制转换std::bind临时对象。
有什么办法可以避免显式的演员吗?
// g++ -std=c++11 test.cxx
#include <functional>
using std::placeholders::_1;
class A
{
public:
void f
#include <functional>
bool f1(int a, int b)
{
return true;
}
int main()
{
// This compiles
std::function<bool()> f2 = std::function<bool()>(std::bind(f1, 1, 2));
std::function<bool()> f1 = f2;
// These don't compile
//std::function<bool()>
考虑下面一些简单的代码:
int f1(int a) {
std::cout << a << std::endl;
}
int main (int agrc, char* argv[]) {
std::function<int(int)> f = std::bind(&f1, std::placeholders::_1);
f(123);
return 0;
}
我已经阅读了一些关于std::function和std::bind的文档,但仍然不了解它是如何工作的。
编译器显示std::bind的调用返回一个_Bind_helper
在c++20中真正令我兴奋的事情之一是std::bind_front。在std::bind和boost::bind中使用占位符确实让我感到困扰,每次调用绑定都会使代码变得越来越混乱。对于我来说,决定启用-std=c++2a并祈祷如果某些事情发生变化,我以后就不必修复代码了,这已经够糟糕的了。
当我意识到我可以做一个在c++17中工作的c++17替代方案时,我正在处理参数包递归,如果我删除了std::invoke,它甚至可以在c++11中工作。
它的编译速度甚至比我的标准库的实现还要快。
//#include
//#include
//of course this would go int
在通过 on std::bind之后,我想知道是否有可能保存由std::bind创建的函数的vector,这样我就可以避免使用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
我无法找到如何使用std::bind将参数绑定到重载的函数。不知何故,std::bind无法推断重载类型(因为它的模板参数)。如果我不过载这个函数,一切都能工作。代码如下:
#include <iostream>
#include <functional>
#include <cmath>
using namespace std;
using namespace std::placeholders;
double f(double x)
{
return x;
}
// std::bind works if this overloaded i
#include <stdio.h>
#include <functional>
void foo(int a, int b)
{
printf("%d %d\n", a, b);
}
int main()
{
using namespace std::placeholders;
auto f1 = std::bind(foo, 10, _1); // fine
std::function<void (int)> f2 = f1; // fine
auto f3 = std::bind(f2, 20
在使用std::function和std::bind升级到XCode 5之后,似乎会生成EXC_BAD_ACCESS异常。看起来好像std::function实现中的__base指针最终为空,导致了错误的访问,但我不清楚为什么会这样。有没有人知道我做错了什么?
下面是说明该问题的示例代码。
struct A
{
void foo(bool b)
{
std::cout << b << std::endl;
}
void go()
{
// ok
auto a = std::bind
我正在编写一个涉及使用f = std::bind(std::bind(std::bind(...)))的模板函数。
但我不确定c++编译器是否足够聪明来展开调用链。
我的意思是:
在创建函子f时,是否有多个std::bind()在运行时调用?
调用f()时,是否涉及在bind_functor对象的不同层调用多个operator()。
举个简单的例子:f2()的运行速度是否略快于f1()?
#include <functional>
int add(int a, int b) {
return a + b;
}
int main() {
using nam
下面是一个简短的样本:
class A {};
class S {};
class B
{
public:
typedef std::function <bool (A& retVal)> property_getter_t;
typedef std::function<bool (B* /*this*/, const std::shared_ptr<S>&, A& retVal)> SettingsPropGetter;
void DefineSettingsProperty(const std::ws