C ++ 11:通用执行程序 [英] C++11: Universal executor

查看:125
本文介绍了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:通用执行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆