首页 > 解决方案 > 指针的函数模板特化

问题描述

在我们的代码库中,我们有一个模板

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);
}

为什么不能将此模板专门用于指针类型?我怎样才能实现专业化?

标签: c++templatestemplate-specialization

解决方案


请注意,在主模板中,const类型DT本身是限定的。假设您想使用类型DTconst 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)

居住


推荐阅读