4
void printVector(vector<int> &data){
        for(auto i : data){
                cout<< i << " ";
        }
        cout<<endl;
}

int main(){
    std::vector<int> data {0,1,2,3,4,5,6,7,8,9};
    vector<int> result;
    result.resize(data.size());
    transform(data.begin(),data.end(),result,bind(std::pow,_1,2));
    return 0;
}

The error thrown is:

stlalgo.cpp:22:61: error: no matching function for call to ‘bind(<unresolved overloaded function type>, const std::_Placeholder<1>&, int)’ 

How do i hint which overloaded function needs to be used in bind?

Cheers!

Ricko M
  • 1,784
  • 5
  • 24
  • 44

1 Answers1

3

You can't pass a function name that designates an overload set as a function pointer. There are several ways to mitigate this. One is a lambda:

transform(data.cbegin(),data.cend(),result.begin(),
    [](int d){ return std::pow(d, 2); });

Another one is to explicitly cast the overload set to the specific function you intend to invoke:

transform(data.cbegin(),data.cend(),result.begin(),
    bind(static_cast<double(*)(double, int)>(std::pow),_1,2));

A third way is to use one of the "lift" macros available, that wrap overload sets into lambdas.

#include <boost/hof/lift.hpp>

transform(data.cbegin(),data.cend(),result.begin(),
    bind(BOOST_HOF_LIFT(std::pow),_1,2));

Note that in all snippets, I have changed the third parameter into result.begin(), as std::transform needs an output iterator there, and the first and second to act on const_iterators.

lubgr
  • 37,368
  • 3
  • 66
  • 117