【发布时间】:2019-04-18 12:36:07
【问题描述】:
我已经开始学习 C++,目前我正在尝试开始使用模板,如果我的措辞不是 100% 准确,请多多包涵。
我正在使用以下文献:
- C++ 模板:完整指南(第 2 版)
- 有效的现代 C++:改进 C++11 和 C++14 使用的 42 种特定方法
第一本书看下面的模板函数
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
现在我想知道,第一个代码 sn-p 的返回类型怎么可能是引用类型?
【问题讨论】:
-
max<const int&, const int&>(42, 51). -
@polygamma 它不会被如此推断,但有人可以像 Jarod 在他们的评论中那样指定它。
-
表达式在 C 或 C++ 中从不具有引用类型(是的,在 C 中没有引用,但类型系统的工作方式相同)
标签: c++ templates reference decltype template-argument-deduction