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

前端 未结 3 1073
太阳男子
太阳男子 2021-01-07 05:21

Assume I have this class (inherited from std::Vector, it\'s just an example)

#include 

using namespace std;

template 
class C          


        
3条回答
  •  庸人自扰
    2021-01-07 06:15

    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.

提交回复
热议问题