运行时获取指定函数参数类型

C++语言 码拜 7年前 (2017-04-15) 825次浏览
有人知道怎么在运行时获得函数参数类型吗。
伪代码是这个意思。

void tFunc(int, int, float) {}
template<T>
int getFuncArgs(T func) {
	int argsCount = getFuncArgsCount(func);
	for (arg : range(argsCount)) {
		auto typeStr = typeid(funcArgs[argsCount]).name();
		print typeStr;
	}	 
}
getFuncArgs(tFunc);

~~~~~~~~~~输出~~~~~~~~~~~~~
int
int
float
c++11应该能写出来,但就是不知道该怎么写。

解决方案

100

#include <iostream>
#include <typeinfo>
void f1() {}
void f2(int) {}
void f3(int, double) {}
void f4(int, double, float) {}
template <typename T>
void print_param(T(*)()) {
    std::cout << "no param\n";
}
/* fold expressing supported in gcc 6
template <typename T, typename... Args>
void print_param(T(*)(Args...)) {
    (std::cout << ... << typeid(Args).name()) << "\n";
}*/
template<typename T>
void print_param_helper() {
    std::cout << typeid(T).name() << "\n";
}
template<typename T, typename U, typename ... Args>
void print_param_helper() {
    std::cout << typeid(T).name() << "\n";
    print_param_helper<U, Args...>();
}
template <typename T, typename... Args>
void print_param(T(*)(Args...)) {
    print_param_helper<Args...>();
}
int main()
{
    print_param(f1);
    print_param(f2);
    print_param(f3);
    print_param(f4);
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明运行时获取指定函数参数类型
喜欢 (0)
[1034331897@qq.com]
分享 (0)