指针的函数模板特化
Function template specialization for pointer
在我们的代码库中有一个模板
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)
在我们的代码库中有一个模板
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)