Thomas Sablik
Thomas Sablik

Reputation: 16448

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?

Upvotes: 2

Views: 261

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

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* (i.e. 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

Upvotes: 6

Related Questions