[英]c++ function pointer to class member compile error for std::string but ok for custom class
我有以下伪代码可以使用std :: function从指向类的函数成员的指针创建可调用对象。
我可以从我的自定义String
类的empty
成员创建一个可调用对象。 但是,当我使用std :: string为空时,它具有编译错误。 我在Xcode和VS2015上都尝试了gcc编译器。
#include <string>
#include <vector>
#include <algorithm>
#include <numeric> //accumulate
#include <iterator> //inserter
#include <functional> //bind, function
struct String {
public:
bool empty() const {
return true;
}
};
int main() {
std::function<bool (const String&)> f = &String::empty; //OK
bool t = f(String()); //implicit parameter 'this' becomes explicit parameter
std::function<bool (const std::string&)> fcn = &std::string::empty; //Compile error
}
编辑:
我正在阅读C ++入门书,并尝试实现这一目标:
std::vector<std::string*> pvec; //use pointer for some reason
std::function<bool (const std::string*)> fcn = &std::string::empty;
std::find_if(pvec.begin(), pvec.end(), fcn);
std::find_if(pvec.begin(), pvec.end(), mem_fn(&std::string::empty));
std::find_if(pvec.begin(), pvec.end(), std::bind(&std::string::empty, std::placeholders::_1));
编辑2:
错误信息:
Undefined symbols for architecture x86_64:
"std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::empty() const", referenced from:
_main in Source.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
编辑3:我尝试过std :: vector,它正在工作。 std :: vector也可以工作
std::function<bool (const std::vector<int> &)> f2 = &std::vector<int>::empty;
bool t2 = f2(std::vector<int>());
std::cout << t2;
std::function<bool (const std::vector<std::string> &)> f3 = &std::vector<std::string>::empty;
bool t3 = f3(std::vector<std::string>());
我用下面的代码行! 在VS2013中,删除&
。
int main() {
std::function<bool (const String)> f = &String::empty; //OK
bool t = f(String()); //implicit parameter 'this' becomes explicit parameter
std::function<bool (const std::string)> fcn = &std::string::empty;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.