Search code examples
c++stlmem-fun

std::transform with virtual call operator throws "global functions do not have 'this' pointers"


PayOff is an abstract base class and CallPayOff and PutPayOff derive from it. The call operator is defined as a pure virtual function in base class and CallPayOff and PutPayoff provide their own implementations.

vector<PayOff*> v;
v.push_back(new CallPayOff(20));
v.push_back(new PutPayOff(20));
vector<double> payVals;
payVals.reserve(v.size());
transform(v.begin(), v.end(), back_inserter(payVals),  bind2nd(mem_fun(&PayOff::operator()),this));

Call operator is defined as:

class PayOff
{
public:
    virtual double operator()(double spot)const = 0;
    virtual ~PayOff(){}
};

Can anyone please take a look? Boost/C++11 is not an option.


Solution

  • You don't say what you expect the transform to do; presumably it's to invoke each PayOff object on some value. In that case the functor should be:

    bind2nd(mem_fun(&PayOff::operator()),some_value)
    

    or, for those not stuck in the past,

    [=](PayOff* p){(*p)(some_value;}}
    

    or

    bind(&PayOff::operator(), _1, some_value);
    

    You are instead trying to bind to this which, in a global function, doesn't exist. In a member function, it would exist, but wouldn't make sense as an argument to a functor that expects a double.