c++ - 使用模板化适配器作为运算符重载实例的 rhs 编译错误

标签 c++ templates compiler-errors operator-overloading

我一直在尝试使用模板化适配器来启用重载运算符。我收到一个编译错误(gcc 4.5.2),这对我来说似乎是矛盾的。我想知道为什么以及如何解决它。下面是说明问题的简化代码。

// The adapter
template <typename T>
class A {
    T t;
public:
    A(T t_) : t(t_) {}
};

// Utility function to return an adaptor
template <typename T>
A<T> make_A(T t) {
    A<T> a(t);
    return a;
}

// The operator overload on the adapter
template <typename T>
A<T> &operator<<(A<T> &a, int) {
    return a;
}

// Shows use case
int main(int,char**) {
    auto aa = make_A(1);
    aa << 2;        // Compiles

    // Desired use:
    make_A(4) << 5; // Compile Error
}

错误信息:

main_operatorinsert.cpp: In function ‘int main(int, char**)’:
main_operatorinsert.cpp:28:22: error: no match for ‘operator<<’ in ‘make_A [with T = int](4) << 5’
main_operatorinsert.cpp:18:11: note: candidate is: A<T>& operator<<(A<T>&, int) [with T = int]

为什么行“aa << 2;”编译,其中行“make_A(4) << 5;”才不是? make_A 返回与 aa 相同的类型。为什么编译器不匹配?我该如何解决这个问题?

最佳答案

make_A返回一个 rvalue,但是你的 operator<<需要一个非常量 lvalue 作为第一个参数。如果你真的需要支持 make_A(4) << 5;,你需要围绕这个重新设计一下你可以制作operator<<一个成员函数,但要注意从它返回一个左值引用是危险的。

关于c++ - 使用模板化适配器作为运算符重载实例的 rhs 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625994/

相关文章:

c++ - 没有匹配的调用函数

c++ - 使用 C++ "Virtual Constructor"通常被认为是好的做法吗?

c++ - 可以在 C++ 中调用缺少模板参数的模板函数吗?

sqlite - 设置Android Studio Room数据库时出现2个实体错误

c++ - 有没有办法在 C++ 应用程序的多次执行中保存一个值?

c# - 在 Word 文档模板中填充表格 C#

javascript - 下划线模板的自定义解析

c++ - 出现错误: “nvlink error : Undefined reference to ' _ZN8Strategy8backtestEPddd'”

c# - 如果我的项目被拆分为多个源文件,如何编译 C# 代码?

c++ -++it 或 it++ 在遍历 map 时?