【发布时间】:2017-05-26 11:17:53
【问题描述】:
我有一个模板类,它在构造函数中接受一个函数指针。类中的方法稍后将根据条件调用该函数。我可以拥有该类的 2 个对象,每个对象都用具有不同签名的函数指针实例化吗?简化代码如下。
#include <iostream>
using namespace std;
template <class FUNC>
class Thread {
public:
Thread(FUNC f1, int i)
: f(f1), val(i) {};
void run() {
if (val == 1)
f();
else
f(val); // here
}
private:
FUNC f;
int val;
};
void print() {
cout << "print" << endl;
}
void incr(int a) {
cout << "incremented value is " << ++a << endl;
}
int main () {
Thread<void(*)()> t1(print,1);
t1.run();
Thread<void(*)(int)> t2(incr,2);
t2.run();
}
run() 根据 val 决定调用哪个函数。两个可能的函数都有不同的签名。执行此操作时出现以下编译错误。
testa.cpp: In member function 'void Thread<FUNC>::run() [with FUNC = void (*)()]':
testa.cpp:33: instantiated from here
testa.cpp:16: error: too many arguments to function
testa.cpp: In member function 'void Thread<FUNC>::run() [with FUNC = void (*)(int)]':
testa.cpp:35: instantiated from here
testa.cpp:14: error: too few arguments to function
我该怎么做? C++ 中有没有办法首先使用模板来做到这一点?
【问题讨论】:
-
1和2是在编译时确定的吗?或者它们必须是运行时的?为什么val存在,是因为要支持两个签名,还是有其他原因? -
你使用的是什么版本的 C++?
-
我正在使用 c++98。 1 和 2 是在编译时确定的。我只使用 val 来区分两种类型的模板类实例化。
-
@vibz:C++98?!你这个可怜的东西。我会看看是否可以更新我的答案以反映您的需求。
标签: c++ templates function-pointers