我想通过使用 typedef
来表示 ptr
参数的类型来简化 foo
。
#include <iostream>
template <unsigned N>
int foo (int (*ptr) (const char (*)[N])) {
char good[N] = "good";
return ptr(&good);
}
int bar (const char (*x)[5]) {
std::cout << *x << "\n";
return 0;
}
int main ()
{
return foo(bar);
}
我想把 foo()
写得更像这样:
template <unsigned N>
int foo (FUNCTION_TYPE *ptr) {
char good[N] = "good";
return ptr(&good);
}
我尝试使用辅助类等特性,but that failed . 是否有适当的方法来创建 typedef
for FUNCTION_TYPE
?
最佳答案
在 C++11 中,您可以使用 using
关键字获得模板 typedef 的粗略等效项。这仍然允许从参数中推导出 N
:
template <unsigned N>
using fooP = int (*) (const char (*)[N]);
template <unsigned N>
int foo (fooP<N> ptr) {
return ptr(0);
}
int bar(const char (*p)[2]) {
return 0;
}
int main() {
return foo(bar);
}
关于c++ - 如何使用 typedef 简化作为函数指针的模板函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17033496/