【问题标题】:c++ overload generic method, by-reference and by-valuec++重载泛型方法,按引用和按值
【发布时间】:2020-10-19 11:23:15
【问题描述】:

我有两个相同的通用方法(编辑:实际上是 operators,但问题是相同的),除了一个通过引用使用其形式参数而另一个方法使用其形式参数按值参数。

struct shout_t {
    template<typename T>
    shout_t& operator<<(T &x) { cout << x; return *this; } // by reference
    
    template<typename T>
    shout_t& operator<<(T x) { cout << x; return *this; } // by value
};

“按引用”方法的目的是允许在不复制的情况下使用“大”对象。 “按值”方法针对的是字面量。

由于“按值”方法可以处理这两种情况(对象本身和文字),这会产生错误:

int main() { // Here "large object" ~ string, "literal" ~ int
    shout_t shout;
    shout << 42; // OK
    shout << "FTL"; // ERROR: Overloaded operator '<<' is ambiguous
}

我正在寻找的行为是如果“按引用”方法适用,请先尝试,如果不适用,请应用“按值”方法。

如何解决这个问题?除了“按值”和“按引用”签名之外,如何获得两个相同的方法的预期行为?

【问题讨论】:

  • 不应该是const T&amp;吗?
  • 你缺少从方法中返回的东西
  • 我试着做一个最小的玩具例子,重点是如何指导编译器选择“预期”方法的问题
  • minimal 很好,但不从声明返回某物的方法返回某物不是“玩具”,它是一种称为未定义行为的野​​兽;)。简化时尽量不要引入额外的问题
  • 你说得对,我忽略了我已经剪掉了这个重要的回报。我现在放回去了。谢谢!

标签: c++ generics reference parameter-passing overloading


【解决方案1】:

这里有两种情况,您可能想要更改作为参数传递的对象,或者您不想。在后一种情况下,作为const-qualified 引用传递:

struct shout_t {
    template<typename T>
    shout_t& operator<<(const T &item) { cout << item; return *this; }
};

否则,将转发引用与std::forward结合使用:

struct shout_t {
    template<typename T>
    shout_t& operator<<(T&& item) { cout << std::forward<T>(item); return *this; }
};

【讨论】:

  • 谢谢!太好了,这解决了我的问题,没有过载,只需使用 const& (facepalm)
猜你喜欢
  • 1970-01-01
  • 2013-03-16
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多