简体   繁体   中英

c++ function pointer to class member compile error for std::string but ok for custom class

I have the following dummy code to use std::function to create a callable from a pointer to function member of class.

I am able to create a callable from my custom String class's empty member. But when I use the std::string's empty instead, it has compile error. I have tried both gcc compiler on Xcode and ms compiler on VS2015.

#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         
}

EDIT:

I am following C++ primer book and I try to achieve this:

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));

EDIT 2:

error message:

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)

EDIT 3: I have tried std::vector and it's working. std::vector is also working

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>());

I use the below code OK! in VS2013, delete & .

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;         
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM