C++查看模板实例化解决指针问题

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,且由于传入的参数为&aconst 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,实参为&aa是一个普通intfunc1是精确匹配,因此输出func1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值