簡體   English   中英

c ++重載泛型方法,按引用和按值

[英]c++ overload generic method, by-reference and by-value

我有兩個相同的通用方法(編輯:實際上是運算符,但方法的問題是相同的),除了一個通過引用使用其形式參數而另一種方法通過值使用其形式參數。

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限定引用傳遞:

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; }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM