【问题标题】:Template Functions and Const/NonConst Reference Parameters模板函数和 Const/NonConst 参考参数
【发布时间】:2011-04-04 11:01:39
【问题描述】:

刚接触 C++ 并从书本中学习,所以我的推理可能相当迂腐或短视。

在模板函数的情况下,我读过当一个参数通过 Reference 传递时,只允许从 Reference / Pointer to NonConst 到 Reference / Pointer to Const 的转换。

这意味着我相信

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

在调用 compare(ci1, ci1) 时应该会失败,其中 ci1 是常量 int,因为 Reference 参数不允许从 Const 转换为 NonCost。

但是它在我的编译器 (Visual C++ 10) 中有效。有人可以解释一下我哪里做错了吗?


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

template <typename T> int compare(T &v1,  T &v2)
{
    // as before
    cout << "compare(T, T)" << endl;
    if (v1 < v2) return -1;
    if (v2 < v1) return 1;
    return 0;
}


const int ci1 = 10;
const int ci2 = 20;

int i1 = 10;
int i2 = 20;

compare(ci1, ci1);     
compare(i1, i1);  

【问题讨论】:

    标签: c++ templates function parameters reference


    【解决方案1】:

    电话

    compare( ci1, ci1 );
    

    将 T 输出为 const int 类型(以您的首选表示法)。

    那么有效的函数签名是

    int compare( int const&, int const& )
    

    您可以使用typeid(x).name() 查看您实际拥有的类型。

    注意:使用 g++ 会产生一些难以理解的短格式,然后您需要使用特殊的 g++ 特定运行时库函数来解码。

    干杯&hth。

    【讨论】:

      【解决方案2】:

      T 将是变量的任何类型 - 在您的情况下为 const int,因此 compare 的最终实例化看起来像

      // T = const int
      int compare(const int& v1, const int& v2)
      

      在你的第一个案例中,compare(ci1,ci2) 和喜欢

      // T = int
      int compare(int& v1, int& v2)
      

      compare(i1,i2).

      【讨论】:

        【解决方案3】:

        在第一种情况下,模板使用T = const int 进行实例化,这很好。

        如果您尝试compare(i1, ci1),您将收到错误消息,因为这将无法找到与int &amp;const int &amp; 兼容的模板参数。将签名更改为 compare(const T &amp;, const T &amp;) 将解决该问题。

        【讨论】:

          【解决方案4】:

          在比较的情况下(ci1, ci1); T 将是 const int。这就是它起作用的原因

          【讨论】:

            【解决方案5】:

            这是可以接受的,因为当您将 int const 替换为 T 时,可以实例化该函数。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-11-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-04-27
              • 2016-05-23
              相关资源
              最近更新 更多