实际上,标题是错误的,C/C++是无法把类型作为参数的,但是可以使用模板技术来实现!。来看个例子:
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T, typename VAL>
ostream &check(int line, VAL val, ostream &out=cout){
if(typeid(T) == typeid(VAL))
out << line << " true " << " ";
else
out << line << " false " << " ";
return out;
}
这个函数的目的就是判断val的类型VAL是否和T相同。调用:
int main(){
int a = 1;
double b = 2;
std::cout << type_name(a) << endl;
check<int>(__LINE__, a) << endl;
check<int>(__LINE__, b) << endl;
return 0;
}
输出:
59 true
60 false
check<int>(__LINE__, a)的<int>使T被推断为int(<int>里的int为显示模板实参,会使模板参数列表<typename T, typename VAL>中的第一个模板参数T推断为int);通过参数a推断出VAL是int,所以typeid(T) == typeid(VAL)为真。
check<int>(__LINE__, b)的<int>使T被推断为int(同上);通过参数b推断出VAL是double,所以typeid(T) == typeid(VAL)为假。
gcc/clang通过typeid(var).name()来获取变量var的类型字符串是不正确的,故补充一个可以正常获取变量类型的字符串的函数type_name:
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
template <typename VAL>
string type_name(VAL &val){
int status;
char* real_name;
real_name = abi::__cxa_demangle(typeid(VAL).name(), nullptr, nullptr, &status);
string s(real_name);
free(real_name);
real_name = nullptr;
return s;
}
int main(){
int a = 1;
double b = 2;
std::cout << type_name(a) << endl;
return 0;
}
参考:
https://bbs.csdn.net/topics/392478020
https://blog.csdn.net/dulq_/article/details/80386295
632

被折叠的 条评论
为什么被折叠?



