c++ - 如何在 C++ 中推断函数参数类型?

标签 c++ function c++11 types

有函数定义:

void f(int) { }

我要定义:

int a;

但如果函数定义更改为:

void f(double) { }

变量定义必须变成:

double a;

即“a”的类型必须与“f”函数的第一个参数相同。 我需要类似以下的东西:

decltype_of_argument<f, 0> a;

在 C++ 中可以吗?

最佳答案

可以通过模板元编程获取类型:

template <class F> struct ArgType;

template <class R, class T> 
struct ArgType<R(*)(T)> {
  typedef T type;
}; 

void f(int) {}

#include <type_traits>
#include <iostream>

int main() {

  // To prove
  std::cout << std::is_same< ArgType<decltype(&f)>::type, int >::value << '\n';

  // To use
  ArgType<decltype(&f)>::type a;
}

根据您想在哪里使用它,您需要将此小模板专门用于其他可调用实体,例如成员函数指针、具有更多参数的函数、仿函数等。Boost 库中有更复杂的方法,请参见例如https://stackoverflow.com/a/15645459/1838266

警告:所有这些实用程序只有在函数/可调用的名称明确映射到单个函数签名时才能工作。如果函数重载或仿函数有多个 operator(),则必须通过显式转换为正确的签名来选择正确的函数/运算符,这使得通过查找签名的一部分模板很没用。这也以某种方式适用于模板,尽管获取显式专用调用的签名可能仍然有用,例如:

template <unsigned N, class F> struct ArgType; //somewhat more sophisitcated 

template <class T> void f(int, T);

ArgType<0, decltype(&f<double>)> //int    - ArgType has it's use here
ArgType<1, decltype(&f<double>)> //double - here it's useless...

关于c++ - 如何在 C++ 中推断函数参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632236/

相关文章:

c++ - 在 C++ Linux 中获取服务状态

c++ - iconv() - 如何确定输出缓冲区所需的大小?

c - 我正在尝试使用 C 编码从 linux 制作 uniq 命令

python - 如何将 python 函数/类/模块对象转换为 python 代码对象

javascript - 确认功能不起作用

c++ - 在运行时选择合适的专用模板

c++ - 有没有办法使用 typedef 中的参数名称

c++ - 类对象初始化

c++ - 最终类的用例

c++ - 需要语法帮助以根据模板参数的类型专门化类方法