如何使用typedef来简化作为函数指针的tempate函数参数 [英] How to use typedef to simplify tempate function argument that is a function pointer

查看:192
本文介绍了如何使用typedef来简化作为函数指针的tempate函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用 typedef 来表示 foo > ptr 参数。

I would like to simplify foo by using a typedef to represent the type for the ptr argument.

#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 code>更像这样:

I would like to write foo() to be more like this:

template <unsigned N>
int foo (FUNCTION_TYPE *ptr) {
    char good[N] = "good";
    return ptr(&good);
}



我尝试使用类似辅助类但失败是否有正确的方法为 FUNCTION_TYPE typedef >

推荐答案

在C ++ 11中,你可以得到一个模板typedef通过使用使用关键字。这仍然允许从参数中推导出 N

In C++11, you can get the rough equivalent of a template typedef by using the using keyword. This still allows N to be deduced from the argument:

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);
}

这篇关于如何使用typedef来简化作为函数指针的tempate函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆