实际上,标题是错误的,C/C++是无法把类型作为参数的,但是可以使用模板技术来实现!。来看个例子:
#include
#include
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
的
使T被推断为int
(
里的int
为显示模板实参,会使模板参数列表
中的第一个模板参数T
推断为int
);通过参数a
推断出VAL是int
,所以typeid(T) == typeid(VAL)
为真。
check
的
使T被推断为int
(同上);通过参数b
推断出VAL是double
,所以typeid(T) == typeid(VAL)
为假。
gcc/clang通过typeid(var).name()
来获取变量var
的类型字符串是不正确的,故补充一个可以正常获取变量类型的字符串的函数type_name
:
#include
#include
#include
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