有函数定义:
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/