简体   繁体   中英

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

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. Suppose you want to specialize it with type DT as const int* (ie pointer to const int ), then the specialization should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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