指针的函数模板特化

Tho*_*lik 2 c++ templates template-specialization

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

template<typename DT>
void f(const DT&) {}
Run Code Online (Sandbox Code Playgroud)

有一些专业。一个专业是

template<>
void f(const int*&) {}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用它时,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&) {}
Run Code Online (Sandbox Code Playgroud)

示例代码是

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

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

int main() {
    const int *a = nullptr;
    f(a);
}
Run Code Online (Sandbox Code Playgroud)

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

son*_*yao 6

请注意,在主模板中,const对类型DT本身进行了限定。假设你想用 type DTas const int*(即指向const int)来特化它,那么特化应该是

template<>
void f(const int* const&) {} // reference to const (pointer to const int)
//                ^^^^^
Run Code Online (Sandbox Code Playgroud)

让我们再次检查主模板,以比较和确认类型:

template<typename DT>
void f(const DT&) {} // reference to const (DT)
Run Code Online (Sandbox Code Playgroud)

居住

  • 或者也许只是“int *const&amp;”,即“DT = int*”。另外,这只是我的观点,但我认为实际上翻转类型中“const”的顺序是更好的风格。如果OP写的是“int const *&amp;”,我认为问题会更清楚。我也认为它读起来更好,根据螺旋规则:`const int *const&amp;`是“对整型常量的常量指针的引用”,但`int const *const&amp;`是“对常量整数的常量指针的引用”。 (5认同)