【发布时间】:2015-11-17 03:57:53
【问题描述】:
我正在使用函数式编程的一些特性,并试图为向量中的每个对象调用一个成员函数。到目前为止,这是我的代码。
emplace.cc
#include <iostream>
#include <vector>
#include <string>
#include <functional>
class Person {
public:
Person(std::string name, size_t age) : _name(name), _age(age) { std::cout << "Hello, " << getName() << std::endl; }
~Person() { std::cout << "Goodbye, "<< getName() << std::endl; }
void greet() { std::cout << getName() << " says hello!" << std::endl; }
std::string getName() const { return _name; }
private:
std::string _name;
size_t _age;
};
int main()
{
std::vector<Person> myVector;
myVector.emplace_back("Hello", 21);
myVector.emplace_back("World", 20);
std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
return 0;
}
这段代码很可能存在问题,但对我来说奇怪的是我正在收到两条错误消息。
emplace.cc:24:4: error: 'for_each' is not a member of 'std'
std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
^
emplace.cc:24:95: error: invalid use of 'this' in non-member function
std::for_each(myVector.begin(), myVector.end(), std::bind1st(std::mem_fun(&Person::greet), this));
^
我正在使用 GCC 5.2.0 编译 -std=c++14。
【问题讨论】:
标签: c++ algorithm functional-programming bind