c++ - 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
}
我正在寻找的行为是首先尝试“按引用”方法是否适用,如果不适用,请应用“按值”方法。
如何解决这个问题?除了“按值”和“按引用”签名之外,如何获得相同的两种方法的预期行为?
解决方案
这里有两种情况,您可能想要更改作为参数传递的对象,或者您不想更改。在后一种情况下,作为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; }
};
推荐阅读
- python - Python 最佳实践:最好使用嵌套函数或私有函数语法?
- javascript - 循环json数据并显示在模态表中
- python - 即使我已经按下它,我的键也不起作用 Python Pygame
- r - ggplot核密度图线重叠不正确
- firebase-realtime-database - 如何从 Firebase 数据库密钥中检索/解码时间戳?
- azure-devops - Azure Devops 中的秘密管道参数
- python - 来自 django auth_user 的用户名作为另一个表中的外键
- python - 如何在列先例中的特定列中查找和查找值并将其值放入 Pandas 的新列中
- android - 我试图将一个应用程序部署到使用 kivy 开发的 google playstore。如何从 API 27 升级到 API 30
- javascript - Vanilla JavaScript 切换功能将我的 h2 标签向上移动