5

我想知道如何得到这个代码编译: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 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; 
} 

错误消息(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' 

我怎样才能显示正确过载的addition函数?

+1

将它转换为正确的指针(有助于对过载),或使用lambda,还有某处的欺骗。 – inf 2013-03-19 17:33:20

+0

尝试此'COUT << universal_exer(的static_cast (&添加),1)<< ENDL;' [示例](https://godbolt.org/g/fLMZRm) – Nyufu 2017-10-02 09:37:41

回答

5

替换你的主与

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

    // or alternatively 
    // cout << universal_exer((int (*)(int))addition, 1) << endl; 
} 
+4

具体地说, '解析重载函数类型'的解决方案是解析*它是哪个*重载函数。这是在这里完成的。 – 2013-03-19 17:38:54