我有一个 C++ 函数声明,需要知道它是如何工作的:
template<class x>
int fun(x, x(*)(x*) );
第一个 arg 是类型 x 的对象。以及如何描述第二个?
最佳答案
这是一个模板函数的声明,该函数返回一个整数并接受一个 x
作为参数,以及一个指向返回一个 x
并接受的函数的指针,作为参数,x*
。
部分 x(*)(x*)
是指“指向返回 x
的函数的指针,并将一个参数作为参数x*
”。第一个x
是返回类型,(*)
表示它是一个指向函数的指针(如果参数有名字,就写成 x(*argname)(x*)
), 第三个 x*
就是参数。
调用它看起来像这样:
int f(int* iptr) { return something; }
fun(4, f); // no need for the explicit template parameter because it can be deduced
或者更一般地
template<typename x>
x functionname(x* xptr) { return something; }
它在 C 中不起作用,因为正如 Daniel White 在评论中所说,C 没有模板。
关于c++ - 奇怪的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8885221/