简体   繁体   English

Function 模板特化指针

[英]Function template specialization for pointer

In our code base we have a template在我们的代码库中,我们有一个模板

template<typename DT>
void f(const DT&) {}

with some specializations.有一些专业。 One specialization is一个专业是

template<>
void f(const int*&) {}

When I try to use it, clang gives me当我尝试使用它时,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&) {}

An example code is示例代码是

template<typename DT>
void f(const DT&) {}

template<>
void f(const int*&) {}

int main() {
    const int *a = nullptr;
    f(a);
}

Why is it not possible to specialize this template for a pointer type?为什么不能将此模板专门用于指针类型? How can I achieve the specialization?我怎样才能实现专业化?

Note that in the primary template, const is qualified on the type DT itself.请注意,在主模板中, const在类型DT本身上是合格的。 Suppose you want to specialize it with type DT as const int* (ie pointer to const int ), then the specialization should be假设您想使用DT类型将其特化为const int* (即指向const int的指针),那么特化应该是

template<>
void f(const int* const&) {} // reference to const (pointer to const int)
//                ^^^^^

Let's check the primary template again, to compare and confirm the type:让我们再次检查主模板,比较并确认类型:

template<typename DT>
void f(const DT&) {} // reference to const (DT)

LIVE居住

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM