【发布时间】:2018-03-07 10:43:21
【问题描述】:
我有以下代码:
#include <iostream>
using namespace std;
template <class T>
int get_num(int k) {
return k + 3;
}
float get_num(float k) {
return k + 3;
}
template <class T1, class T2>
void function(T1 (*callback)(T2), T2 arg) {
callback(arg);
}
int main() {
// your code goes here
function(get_num, 3);
return 0;
}
我需要使用 int 参数调用 get_num() 函数。但是编译器得到这个错误:
prog.cpp: In function ‘int main()’: prog.cpp:21:21: error: no matching function for call to ‘function(<unresolved overloaded function type>, int)’ function(get_num, 3); ^ prog.cpp:15:6: note: candidate: template<class T1, class T2> void function(T1 (*)(T2), T2) void function(T1 (*callback)(T2), T2 arg) { ^~~~~~~~ prog.cpp:15:6: note: template argument deduction/substitution failed: prog.cpp:21:21: note: couldn't deduce template parameter ‘T1’ function(get_num, 3);
怎么做?
【问题讨论】:
-
这是
template <class T>故意的吗? -
你的意思是为什么要写 class 而不是 typename ?
-
不,我的意思是如果
int get_num(int k)应该是一个函数或一个模板。它看起来有点像它的常规功能。 -
@ՎարդանԳրիգորյան 第 3 行(实际上是前 3 行)看起来不属于这里,是吗?
标签: c++ function c++11 templates callback