How to use a function of own class in for_each method?

无人久伴 提交于 2019-12-01 00:31:15

C++11 bind solution:

std::for_each(this->begin(), this->end(),
      std::bind(&C::transformation, this, std::placeholders::_1));

C++11 lambda solution:

std::for_each(this->begin(), this->end(),
      [this] (T& i) { transformation(i); });

C++14 generic lambda solution:

std::for_each(this->begin(), this->end(),
      [this] (auto&& i) { transformation(std::forward<decltype(i)>(i)); });

C++98 bind1st+mem_fun solution:

std::for_each(this->begin(), this->end(),
      std::bind1st(std::mem_fun(&C::transformation), this));

Note: this->begin() and this->end() calls are qualified with this-> only because in the OP's code they are member functions of a templated base class. As such, those names are primirarily searched in a global namespace. Any other occurrence of this is mandatory.

For starters, don't inherit from the standard containers, they are not designed to be inherited (no virtual destructors etc.).

Secondly, and regarding your problem, it's because a pointer to a member function is not the same as a pointer to a function. The reason is that member function has a hidden first parameter which becomes the this pointer in the function. The simplest way to solve it is to make the function static.

Another solution is to use the std::bind function that came with C++11:

for_each(this->begin(), this->end(),
    std::bind(&C::transformation, this, std::placeholders::_1));

If you don't have C++11 (even though you tagged your question as such), then you probably could get something working with std::mem_fun or std::bind1st.

You need to bind the this pointer:

public:   
void method() 
{
    for_each(this->begin(), this->end(), bind(&C::transformation, this, placeholders::_1));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!