有人知道怎么在运行时获得函数参数类型吗。
伪代码是这个意思。
伪代码是这个意思。
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);
}