c++中可调整函数对象的编译错误
Compilation error with adaptable function objects in c++
我正在学习如何在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_fn
的argument_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中被删除。
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?