c++中可调整函数对象的编译错误

Compilation error with adaptable function objects in c++

本文关键字:编译 错误 对象 函数 可调整 c++      更新时间:2023-10-16

我正在学习如何在c++中使用标准泛型算法。在下面的代码示例中,我试图在自定义组合函数的帮助下将字符串转换为double,该函数将两个操作(string to const char* and const char* to double)组合为一个。

我把unary_composer写成一个可适应的函数对象。

然而,当我编译它,我得到以下错误

错误2错误C2664: 'double unary_composer::operator ()(conststd::basic_string<_Elem,_Traits,_Ax> *)':不能转换参数1从'std::basic_string<_lem,_Traits,_Ax>'到'conststd:: basic_string<_Elem、_Traits _Ax> *

using namespace std;
template<typename F1, typename F2>
class unary_composer : public unary_function<typename F2::argument_type, typename F1::result_type>
{
    F1 f1;
    F2 f2;
public:
unary_composer(F1 lf1, F2 lf2) : f1(lf1), f2(lf2){}
typename F1::result_type operator()(typename F2::argument_type x)
{
   return f1(f2(x));
}
};
template <typename F1, typename F2>
unary_composer<F1, F2> compose(F1 fone, F2 ftwo)
{
   return unary_composer<F1, F2>(fone, ftwo);
}
int _tmain(int argc, _TCHAR* argv[])
{
   const int SZ = 9;
   vector<string> vs(SZ);
   srand(time(0));
   generate(vs.begin(), vs.end(), NumGenerator()); // Generates strings with random digits ex: "12.35". NumGenerator is defined in another source file.
   vector<double> vd;
   // Transform the strings to doubles
   transform(vs.begin(), vs.end(), back_inserter(vd), compose(ptr_fun(atof), mem_fn(&string::c_str)));
   copy(vd.begin(), vd.end(), ostream_iterator<double>(cout, " ")); // print to console
   cout<<endl;
   return 0;
}

当我使用mem_fun_ref代替mem_fn时,它工作得很好。也许,错误说unary_composer's运算符函数期望const string*类型的参数,但字符串正在传递。但我不知道怎么补救。我错过了什么?

PS:这个例子摘自《Thinking in c++ vol . 2》(第六章)

std::mem_fnargument_type是指向类型的指针,这打破了你的unary_composer使用它作为它的own argument_type

根据编译器对c++ 11的支持级别,您可以将编写器更改为

之类的内容。
template<typename F1, typename F2>
class unary_composer
{
    F1 f1;
    F2 f2;
public:
    unary_composer(F1 lf1, F2 lf2) : f1(lf1), f2(lf2){}
    template <typename ARG>
    auto operator()(ARG x)->decltype(f1(f2(x))
    {
        return f1(f2(x));
    }
};

并像这样调用它:

transform(vs.begin(), vs.end(), back_inserter(vd),
          compose(std::atof, mem_fn(&string::c_str)));

查看工作示例。

为了完整起见,这里有一个不需要推出任何函子的版本:

transform(vs.begin(), vs.end(), back_inserter(vd),
         [](const std::string& s)
         {return std::stod(s);});

注意mem_fun, mem_fun_ref, unary_functor和其他自c++ 11以来已弃用,并且很可能在c++ 17中被删除。