我开始学习C++,目前正在尝试使用模板,如果我的措辞不是100%准确,请谅解。
我正在使用以下资料:
并且说明这个定义有一个缺陷,因为
我正在使用以下资料:
- C++ Templates: The Complete Guide(第二版)
- Effective Modern C++:42种改进你对C++11和C++14的使用方法
template<typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(b<a?a:b) {
return b < a ? a : b;
}
并且说明这个定义有一个缺陷,因为
T1
或T2
可能是一个引用类型,所以返回类型也可能是引用类型。
然而,第二本书指出,如果ParamType
(在我们的情况下是T1
和T2
)既不是指针类型也不是引用类型,那么调用表达式中的引用部分将会被忽略。
通过以下例子进行说明:
template<typename T>
void f(T param);
int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before
f(x); // T's and param's types are both int
f(cx); // T's and param's types are again both int
f(rx); // T's and param's types are still both int
现在我在想,第一个代码片段的返回类型怎么可能是引用类型呢?
max<const int&, const int&>(42, 51)
. - Jarod42