重载函数模板 从C++ C++模板中读取重载函数模板:完整的指南,我遇到下面的例子: // maximum of two values of any type template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } // maximum of two pointers template <typename T> inline T* const& max (T* const& a, T* const& b) { return *a < *b ? b : a; } // maximum of two C-strings inline char const* const& max (char const* const& a, char const* const& b) { return std::strcmp(a,b) < 0 ? b : a; } int main () { int a=7; int b=42; ::max(a,b); // max() for two values of type int std::string s="hey"; std::string t="you"; ::max(s,t); // max() for two values of type std::string int* p1 = &b; int* p2 = &a; ::max(p1,p2); // max() for two pointers char const* s1 = "David"; char const* s2 = "Nico"; ::max(s1,s2); // max() for two C-strings } //任何类型的最大值为两个 样板 内联T常数和最大值(T常数和a、T常数和b) { 返回a

重载函数模板 从C++ C++模板中读取重载函数模板:完整的指南,我遇到下面的例子: // maximum of two values of any type template <typename T> inline T const& max (T const& a, T const& b) { return a < b ? b : a; } // maximum of two pointers template <typename T> inline T* const& max (T* const& a, T* const& b) { return *a < *b ? b : a; } // maximum of two C-strings inline char const* const& max (char const* const& a, char const* const& b) { return std::strcmp(a,b) < 0 ? b : a; } int main () { int a=7; int b=42; ::max(a,b); // max() for two values of type int std::string s="hey"; std::string t="you"; ::max(s,t); // max() for two values of type std::string int* p1 = &b; int* p2 = &a; ::max(p1,p2); // max() for two pointers char const* s1 = "David"; char const* s2 = "Nico"; ::max(s1,s2); // max() for two C-strings } //任何类型的最大值为两个 样板 内联T常数和最大值(T常数和a、T常数和b) { 返回a,c++,stl,C++,Stl,我不了解char const*const的含义和用途&它用于普通max函数的返回类型以及参数类型。即使我们使用char const*,它也可以正常工作 re “我不了解char const*const的含义和用途&它用于普通max函数的返回类型以及参数类型。即使我们使用char const*,它也可以正常工作 它可能在书中解释(然后是为了教学目的,只是一个坏例子),也可能是纯粹的愚蠢 如果您不关心非常严格地应用指导规则,或者在形式参数上没有这样的const规则,那么就没有理由不使用char-co

我不了解char const*const的含义和用途&它用于普通max函数的返回类型以及参数类型。即使我们使用char const*,它也可以正常工作

re

我不了解char const*const的含义和用途&它用于普通max函数的返回类型以及参数类型。即使我们使用char const*,它也可以正常工作

它可能在书中解释(然后是为了教学目的,只是一个坏例子),也可能是纯粹的愚蠢

如果您不关心非常严格地应用指导规则,或者在形式参数上没有这样的
const
规则,那么就没有理由不使用
char-const*const
,甚至只使用
char-const*


如果是教学性的,那么请注意所有三个重载对于形式参数类型都具有相同的形式,即
T const&

当您想从模板代码中获取其中一个的地址时,这会有所帮助


我之所以提到这一点,是因为这本书是Josuttis和Vandevorde(Daveed)写的,他们很少做傻事。

因为你在这本书的函数模板和重载解析部分找到了这一点,这个例子的重点是说明选择哪些函数来进行重载解析。为了说明非模板化函数是首先考虑的,无论模板化函数匹配得多么好,他们已经为
char const*const&
构建了最大示例。相反,如果函数签名是
char const*
,那么它就没有教育意义了-模板函数都不是匹配的。

是的,在实践中,通过常量引用返回指针是没有意义的


但这里是本书关于函数模板重载的部分,我认为它只是用于拟合函数模板
max
的返回值的定义,它是一个常量引用,如
T const&
。所以正常的
max
函数(对于类型
char const*
)的返回值应该是
char const*const&

通过常量引用传递指针并不能真正实现任何功能。但这个示例直接取自本书。