C ++ 11:通用执行程序

编程入门 行业动态 更新时间:2024-10-27 01:29:27
本文介绍了C ++ 11:通用执行程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道如何获取此代码编译:

// test3.cpp #include< iostream> using namespace std; template< typename R,typename ... rArgs> R universal_exer(R(* f)(rArgs ...),rArgs ... args) { return(* f)(forward< rArgs>(args)... ); } int add(int a) { return a; } int add(int a,int b) { return a + b; } template< typename ... Args> int add(int a,int b,Args ... args) { return a + b + addition(args ...) } int main() { cout<< universal_exer(& addition,1)<< endl }

错误讯息(gcc 4.7.2):

test3.cpp:在函数'int main()': test3.cpp:31:40:error: 'universal_exer(<未解析的重载函数类型>,int)' test3.cpp:31:40:note:候选项是: test3.cpp:8:3:note:template& class ... rArgs> R universal_exer(R(*)(rArgs ...),rArgs ...) test3.cpp:8:3:note:模板参数扣除/替换失败: test3.cpp:31: 40:注意:无法推导出模板参数'R'

int main() { int(* f)(int)=& addition; cout<< universal_exer(f,1)<< endl //或者 // cout<< universal_exer((int(*)(int))addition,1)< endl }

I would to know how get this code compiles:

// test3.cpp #include <iostream> using namespace std; template<typename R, typename... rArgs> R universal_exer(R(*f)(rArgs...), rArgs... args) { return (*f)(forward<rArgs>(args)...); } int addition(int a) { return a; } int addition(int a, int b) { return a + b; } template<typename... Args> int addition(int a, int b, Args... args) { return a + b + addition(args...); } int main() { cout << universal_exer(&addition, 1) << endl; }

Error message (gcc 4.7.2):

test3.cpp: In function 'int main()': test3.cpp:31:40: error: no matching function for call to 'universal_exer(<unresolved overloaded function type>, int)' test3.cpp:31:40: note: candidate is: test3.cpp:8:3: note: template<class R, class ... rArgs> R universal_exer(R (*)(rArgs ...), rArgs ...) test3.cpp:8:3: note: template argument deduction/substitution failed: test3.cpp:31:40: note: couldn't deduce template parameter 'R'

How can I indicate the correct overload of the addition function?

解决方案

Replace your main with

int main() { int (*f)(int) = &addition; cout << universal_exer(f, 1) << endl; // or alternatively // cout << universal_exer((int (*)(int))addition, 1) << endl; }

更多推荐

C ++ 11:通用执行程序

本文发布于:2023-11-13 09:29:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!