c++ - 如何使用 typedef 简化作为函数指针的模板函数参数

标签 c++

我想通过使用 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/

相关文章:

c++ - 回文和镜像字符串

c++ - 使用 Debian Box 中的 Eclipse CDT 构建 TFS

c++ - 如何在与定义分离的 void 上实现部分专用模板?

c++ - 将lambda参数传递给没有中间变量的std::function参数

c++ - 您能否推荐任何使用单元测试对源代码进行广泛测试的开源项目?

c++ - 模板推导/替换在智能指针上失败

c++ - 父对象调用子方法C++

c++ - 用户空间中的 Linux C/C++ 计时器信号处理程序

c++ - 运算符重载模板参数

c++ - OpenCV: ‘SiftDescriptorExtractor’ 未在此范围内声明