在调用运算符重载时识别调用上下文/用法C++



无论我想要的是否是不良做法,我想知道是否可以区分以下情况:

MyType A, B, C;  
Case1:  
    B  << A;    
Case2:
    C << (B << A);

我在案例 1 中想要的是 B 被修改,以便它与 A 连接。另一方面,在 Case2 中,我希望 B 不会被修改,而是返回一个等效于"B 与 A 连接"的临时对象(并且 C 被修改并与该临时对象连接(。

这可能吗?如果是这样,运算符重载语法和变体应该是什么C++?我尝试了运算符 RHS 参数的 r 值版本;和常量/非常量过载;以及&/&&后固定的方法,以区分过载操作员的LHS。

有什么想法吗?(我真的尝试了很多避免重复的问题(

您可以使用另一种类型来执行此操作。

#include <string>
#include <iostream>
template<typename T>
class MyTypeHelper
{
public:
    T x;
    T* y;
    MyTypeHelper(T* t) : x(*t), y(t)
    {
    }
};
class MyType
{
public:
    std::string x;
    MyTypeHelper<MyType> operator<<(MyType& i)
    {
        MyTypeHelper<MyType> h(this);
        x += i.x;
        return h;
    }
    MyTypeHelper<MyType> operator<<(MyTypeHelper<MyType>& i)
    {
        MyTypeHelper<MyType> h(this);
        x += i.y->x;
        *(i.y) = i.x;
        return h;
    }
};
int main(int argc, char* argv[])
{
    {
        MyType A, B, C;
        A.x = "A";
        B.x = "B";
        C.x = "C";
        B << A;
        std::cout << A.x << " " << B.x << " " << C.x << std::endl;
    }
    {
        MyType A, B, C;
        A.x = "A";
        B.x = "B";
        C.x = "C";
        C << (B << A);
        std::cout << A.x << " " << B.x << " " << C.x << std::endl;
    }
    return 0;
}

最新更新