gpt4 book ai didi

c++ - 指针的函数模板特化

转载 作者:行者123 更新时间:2023-12-01 18:57:21 26 4
gpt4 key购买 nike

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

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)

LIVE

关于c++ - 指针的函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61525482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com