c ++中自适应函数对象的编译错误

Compilation error with adaptable function objects in c++

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

我已经写了unary_composer作为适应性函数对象

但是当我编译它时,我遇到了以下错误

Error 2 error C2664: 'double unary_composer::operator ()(const std::basic_string<_Elem,_Traits,_Ax> *)' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const std::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 opeartor 函数期待 const string* 类型的参数,但正在传递字符串。但我不知道如何修复它。我哪里漏了?

PS: 示例取自 Thinking in C++ vol2 (chapt 6)

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

看到一个working example.

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

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

请注意,mem_funmem_fun_refunary_functor 和其他自 C++11 起已弃用,很可能会在 C++17 中删除。