首页 > 解决方案 > c++重载泛型方法,按引用和按值

问题描述

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

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
}

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

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

标签: c++genericsreferenceparameter-passingoverloading

解决方案


这里有两种情况,您可能想要更改作为参数传递的对象,或者您不想更改。在后一种情况下,作为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; }
};

推荐阅读