C++查看模板实例化解决指针问题
查看模板实例化的方法
clang++ -Xclang -ast-print -fsyntax-only example.cc
其中example.cc
是想查看模板实例化的文件
遇到的指针问题
#include <iostream>
template <typename T> void debug_rep(const T &t) {
std::cout << "func1" << std::endl;
}
template <typename T> void debug_rep(const T *t) {
std::cout << "func2" << std::endl;
}
int main() {
int a = 2;
debug_rep(&a);
return 0;
}
本以为会实例化如下这样:
template <> void debug_rep<int *>(const int *&t) // func1
template <> void debug_rep<int>(const int *t) // func2
如果是这样按照模板应选择更特例化的规则应选择func2
,且由于传入的参数为&a
,const int *&t = &a;
是错误代码,因为t
是一个指向const int
的指针的引用,不能直接绑定到一个地址值上(除非是const指针),因此更应选择func2
,然而,输出结果为func1
。
解决思路
查看模板实例化了哪些版本,输出如下:
template <typename T> void debug_rep(const T &t) {
std::cout << "func1" << std::endl;
}
template<> void debug_rep<int *>(int *const &t) {
std::cout << "func1" << std::endl;
}
template <typename T> void debug_rep(const T *t) {
std::cout << "func2" << std::endl;
}
template<> void debug_rep<int>(const int *t)
int main() {
int a = 2;
debug_rep(&a);
return 0;
}
可以看到,const T &t
实例化int *
是int *const &t
。
因为T
是一个整体,即实例化可以看成const (int *) &t
,这种写法是错误的,但是表达的意思是,t
是一个指针的引用,这个指针是const
的,指向int
,于是应该写成int *const &t
。
此时因为func1
的形参为:指向int
的常量指针的引用t
,而func2
的形参为:指向const int
的指针t
,实参为&a
,a
是一个普通int
,func1
是精确匹配,因此输出func1
。