【发布时间】:2013-12-15 14:07:04
【问题描述】:
这是我正在尝试做的一个简单(也是一个愚蠢的)示例:
#include <iostream>
void callFunctionsFromAnArray(void *(*)(int), int);
void f1(int);
void f2(int);
void f3(int);
int main()
{
const int n = 3;
void (*functions[n]) (int) = { f1, f2, f3 };
callFunctionsFromAnArray(functions, n);
}
void callFunctionsFromAnArray(void *(*f) (int), int fCount) {
for (int i = 0; i < fCount; i++)
f[i](1);
}
void f1(int a)
{
std::cout << a * 1 << '\n';
}
void f2(int a)
{
std::cout << a * 2 << '\n';
}
void f3(int a)
{
std::cout << a * 3 << '\n';
}
这些是我在尝试编译时遇到的错误:
12:9: error: no matching function for call to 'callFunctionsFromAnArray'
callFunctionsFromAnArray(functions, n);
3:10: note: candidate function not viable: no known conversion from 'void (*[3])(int)' to 'void *(*)(int)' for 1st argument
void callFunctionsFromAnArray(void *(*)(int), int);
17:13: error: subscript of pointer to function type 'void *(int)'
f[i](1);
2 errors generated.
但是,如果我将参数更改为 void (*f[3]) (int) 它可以工作。但问题是,在运行时之前并不总是可以知道数组的大小(这就是为什么函数毕竟有第二个参数)。有什么解决办法吗?
【问题讨论】:
-
对函数类型使用
typedef通常是个好主意,以帮助避免这个问题。 -
std::vector的std::function怎么样?
标签: c++ argument-passing