【问题标题】:Why are reference template parameters not deduced automatically?为什么不自动推导出参考模板参数?
【发布时间】:2017-09-21 12:11:00
【问题描述】:

在下面的示例中,我直观地希望对inc(iref) 的调用会调用带有T=int& 的inc 函数,因为这是iref 的类型。但是,似乎& 在将变量传递给函数时被删除,因此在inc(i)inc(iref) 的情况下导致T=int。我期望的行为仅在显式指定模板参数作为参考时才会发生。

template<typename T> 
void inc(T t) {
    t++;
}

int main() {
    int i = 41;
    int& iref = i;

    iref++;
    std::cout << i << " " << iref << std::endl; // prints 42 42, as expected

    inc(i);
    std::cout << i << " " << iref << std::endl; // still prints 42 42, as expected

    inc(iref);
    std::cout << i << " " << iref << std::endl; // prints 42 42, instead of 43 43

    inc<int&>(iref);
    std::cout << i << " " << iref << std::endl; // now finally prints 43 43
}

所以,我的问题是:

  • 为什么引用在通过inc(iref) 传递时似乎变成了“裸”值?其背后的流程是什么?
  • 为什么会以这种方式工作/该设计决策背后的基本原理是什么?如果按照我直觉预期的方式工作,会不会有任何问题或负面后果?

【问题讨论】:

  • 你的方式是如何通过副本的?
  • 你想念inc&lt;int&amp;&gt;(i);
  • “为什么它会这样工作/这个设计决策背后的基本原理是什么?” 我想这还没有回答,我不会结束这个问题。
  • @VittorioRomeo:没错,这就是最初发布这个问题的主要动机。问题的第一部分似乎在 NathanOliver 链接的问题中得到了回答:C++ 将所有表达式视为具有非引用类型。
  • 因为通常由模板编写者而不是模板用户来决定模板是实现值传递还是引用传递更有意义。

标签: c++ reference


【解决方案1】:

引用被剥夺了它的引用值,因为如果它不是 iref 则不明确(int& 或 int)。它是这样设计的,这样你就可以像这样重载它:

#include <iostream>

template<typename T> 
void inc(T& t) {
    t++;
}

int main() {
    int i = 41;
    int& iref = i;

    inc(iref);
    std::cout << iref << std::endl;
}

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多