gpt4 book ai didi

c++ - C++ 函数模板特化是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-04 15:58:45 24 4
gpt4 key购买 nike

我正在阅读 C++ Primer (5th Edition) , 16.5, Defining a Function Template Specialization, 对作者给出的例子感到困惑,我们来看下面的模板函数:

template <typename T> int compare(const T&, const T&);

及其特化版本:

template <>
int compare(const char* const &p1, const char* const &p2)
{
return strcmp(p1, p2);
}

T 的类型将是 const char * ,但我不认为该函数可能是模板函数的特化版本,因为我认为 const char* const &p1只能是T const &的特化但是const T & ,我知道我错了,但我想知道我为什么错了。

编辑:

有一点要强调,如果我调用 compare("hi", "mom") ,它不会编译,也就是说,template <typename T> int compare(const T&, const T&)无法初始化为 int compare(const char* const &p1, const char* const &p2) , 我知道 T将用 char[3] 初始化或 char[4] ,但既然这不会编译,为什么编译器不会忽略这种初始化而是选择一个会编译的初始化?

最佳答案

在 C++ 中,const TT const 的意思完全一样。因此 const T &T const & 的意思完全一样。

它真的不可能是任何其他方式,因为引用永远不能更改为引用其他内容(它们不是“可重新定位的”)。如果您将 T const & 读作“不能更改为引用不同 T 的引用”,那是不正确的。它是“对 T 的引用,不能用于修改该 T(并且与所有引用一样,不能更改为引用不同的 T)。”

关于c++ - C++ 函数模板特化是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583480/

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