为什么不能将绑定的成员函数作为可调用函数传递?

时间:2018-10-28 23:05:26

标签: c++

此代码是编译错误:

std::string str("hello world"); 
std::unordered_set filter{'h', 'w', ' '};
str.erase(std::remove_if(str.begin(), str.end(), filter.count), str.end());

我知道可以用lambda来完成,但是为什么不允许这样呢?在Java中工作正常。

4 个答案:

答案 0 :(得分:4)

  

为什么不能将绑定的成员函数作为可调用函数传递?

可以将绑定的成员函数传递为可调用的。

只是成员访问运算符(.)不会将对象绑定到函数并返回绑定的那个。

您可以使用std::bind绑定成员函数(指针):

using namespace std::placeholders;
std::remove_if(str.begin(), str.end(),
    std::bind(&std::unordered_set<char>::count, filter, _1))

尽管如此,这比使用lambda更好。

答案 1 :(得分:1)

C ++不能那样工作。您需要使用std::bind明确指定要从中调用方法的对象。

#include <string>
#include <unordered_set>
#include <algorithm>
#include <functional>

int main() {
    using namespace std::placeholders;

    std::string str("hello world"); 
    std::unordered_set<char> filter{'h', 'w', ' '};
    str.erase(std::remove_if(str.begin(), str.end(), std::bind(&std::unordered_set<char>::count, &filter, _1)), str.end());
}

答案 2 :(得分:1)

刚刚发现C ++ 20引入了std::bind_front,这有点简单:

str.erase(std::remove_if(str.begin(), str.end(), std::bind_front(&std::unordered_set<char>::count, filter)), str.end());

答案 3 :(得分:-1)

filter.count不是函数指针,因此不能作为参数传递。

您可以使用lambda (since C++11)来捕获filter转发成员函数count的参数。

std::string str("hello world"); 
std::unordered_set filter{'h', 'w', ' '};    
str.erase(
    std::remove_if(str.begin(), str.end(), [&](auto &each) noexcept {
        return filter.count(each);
    }), str.end());
相关问题