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)
为什么不能将此模板专门用于指针类型?我怎样才能达到专业化?
请注意,在主模板中,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)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |