c++ - 指针的函数模板特化
问题描述
在我们的代码库中,我们有一个模板
template<typename DT>
void f(const DT&) {}
有一些专业。一个专业是
template<>
void f(const int*&) {}
当我尝试使用它时,clang给了我
error: no function template matches function template specialization 'f'
void f(const int*&) {}
note: candidate template ignored: cannot deduce a type for 'DT' that would make 'const DT' equal 'const int *'
void f(const DT&) {}
示例代码是
template<typename DT>
void f(const DT&) {}
template<>
void f(const int*&) {}
int main() {
const int *a = nullptr;
f(a);
}
为什么不能将此模板专门用于指针类型?我怎样才能实现专业化?
解决方案
请注意,在主模板中,const
类型DT
本身是限定的。假设您想使用类型DT
为const int*
(即指向的指针const
int
)专门化它,那么专门化应该是
template<>
void f(const int* const&) {} // reference to const (pointer to const int)
// ^^^^^
让我们再次检查主模板,比较并确认类型:
template<typename DT>
void f(const DT&) {} // reference to const (DT)
推荐阅读
- python - cuda-cross-aarch64 是通过 conda、conda-forge 通道安装的 cudatoolkit 的一部分吗?
- node.js - 是否可以通过 Windows 服务器上的 Puppeteer 连接到 NordVPN?
- html - 使用网格模板区域的项目布局
- javascript - client.on() 不触发
- swift - Swift 中泛型声明中的数组
- excel - INDIRECT excel函数的使用
- laravel - laravel 中特定项目的权限和角色?
- java - 如何在一个句子中多次使用参考文献?
- r - 合并 2 个具有公共列的数据框,并在公共值不为 NA 时添加指示符
- elisp - Numerate the org headings