由于无法解析重载函数,导致C ++绑定失败

时间:2019-05-29 09:01:10

标签: c++

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;
}

引发的错误是:

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

我如何提示在绑定中需要使用哪个重载函数?

干杯!

1 个答案:

答案 0 :(得分:3)

您不能传递将重载集指定为函数指针的函数名称。有几种方法可以减轻这种情况。一个是lambda:

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

另一种方法是将重载集显式转换为要调用的特定函数:

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

第三种方法是使用可用的“提升”宏之一,该宏将重载集包装到lambda中。

#include <boost/hof/lift.hpp>

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

请注意,在所有代码段中,我都将第三个参数更改为result.begin(),因为std::transform在那里需要一个输出迭代器,而第一个和第二个要对const_iterator起作用。 / p>