构造std::函数的向量时出现编译器错误
Compiler error when constructing a vector of std::function
请有人帮助解释为什么我在OS X上使用Xcode 5.1编译以下代码时出错。Apple LLVM版本5.1(clang-503.0.40)(基于LLVM 3.4svn)。
#include <vector>
#include <functional>
void func1(const std::string& value)
{
// ...
}
void func2(const std::string& value, int min, int max)
{
// ...
}
class X
{
public:
void x1(const std::string& value)
{
// ...
}
void x2(const std::string& value, int min, int max)
{
// ...
}
};
const std::vector<std::function<void(std::string)>> functions
{
func1,
std::bind(func2, std::placeholders::_1, 5, 6),
std::mem_fn(&X::x1), // compiler error
};
报告的错误为:
no matching constructor for initialization of 'const std::vector<std::function<void (std::string)> >'
const std::vector<std::function<void(std::string)>> functions
此外,我想把X::x2加到向量上。我该怎么做?
谢谢。
std::mem_fn
所做的是,它返回一些未指定的对象,该对象可使用与传入的成员函数或成员变量所属类型相同的指针或引用类型(甚至智能指针类型)的附加第一个参数调用(所有其他参数都被转发)。这意味着您可以将该对象存储在如下所示的函数包装器中:
std::function<void(X*,const std::string&)> f = std::mem_fn(&X::x1);
然后用一个实际的参数调用它:
X x{};
f(&x, "foo"); // or std::mem_fn(&X::x1)(&x, "foo");
与相同
(&x)->x1("foo");
换句话说,在将可调用对象存储在std::function<void(const std::string&)>
的std::vector
中时,这很可能不是您想要的。与其添加额外的第一个参数,不如将其与将调用该函数的上下文绑定:
X x{}; // object in context of which the function will be called
const std::vector<std::function<void(std::string)>> functions
{
func1,
std::bind(func2, std::placeholders::_1, 5, 6),
std::bind(&X::x1, &x, std::placeholders::_1),
// ~~~~~~~~^ ~~~~~^ ~^ ~~~~~~~~~~^
// bind function with object x and actual argument to be forwarded
};
DEMO
相关文章:
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++,我收到一个无法理解的编译器错误
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 重载方法的方式会在使用临时调用时生成编译器错误
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 编译器错误:destuctor 的更宽松的抛出说明符
- Android NDK clang 编译器错误在 Windows 上显示'No such file or directory'
- C++ G++ 编译器 - 错误:隐式声明的定义
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 模板模板参数和模板别名:编译器错误?
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- C1001内部编译器错误是由于矢量初始化(如数组)引起的
- 编译器错误(英特尔并行工作室 2019 与 Visual Studio 社区 2019)
- 如何在C++中克服此 C4430 编译器错误?
- 尝试使用 WinBGI 显示文本时出现编译器错误
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- C++自定义分配器大小参数作为模板参数会引发编译器错误