如何重载逗号运算符以将值分配给数组

How to overload a comma operator to assign values to an array

所以我得到了以下代码:

#include <map>
#include <iostream>
using namespace std;

template<class V, unsigned D>
class SparseArray
{
public:

    map<string,V> data;

    SparseArray(){}

    class Index
    {
    private:
        int dims[D]{};
    public:
        int& operator[](int index)
        {
            return dims[index];
        }

        const int& operator[](int index) const
        {
            return dims[index];
        }

        friend ostream& operator<<(ostream& os, const SparseArray<V,D>::Index& index)
        {
            os << '{';
            for(int i=0;i<D;i++)
            {
                os<<index.dims[i];
                if(i+1!=D)os<<',';
            }
            os << '}';
            return os;
        }
        Index operator,(Index index)
        {

        }

        Index(){for(int i=0;i<D;i++){dims[i]=0;}}
    };

};

int main()
{
SparseArray<int,3>::Index i;

i[0] = 1;
i[1] = 2;
i[2] = 7;

//i = 1,2,7; - that's what i'm trying to make work

cout<<i;
}

我如何实现逗号运算符,以便 i=1,2,7 将执行与 i[0] = 1; i[1] = 2; i[2] = 7; 完全相同的操作 到目前为止我所知道的是 i=1,2,7 等同于 i.operator=(1).operator,(2).operator,(7); ,我该如何使用它? 我从研究中知道重载逗号运算符是不寻常的,但我需要这样做,因为它符合项目的要求。

How do I implement the comma operator so that obj = 1, 2, 7 will do the exact same thing as doing obj.arr[0] = 1; obj.arr[1] = 2; obj.arr[2] = 7;?

这将完全改变 comma operator 的含义。我更喜欢初始化列表:

obj = {1, 2, 7};

在此场景中使用逗号运算符。

I know from research that overloading comma operator is unusual, yet I need to do it as it's in the requirements of the project.

是的,我遇到过这样的老师。我认为他们只是想测试你是否可以在这些奇怪的约束下破解他们的任务。而我的解决方案是基于你问题本身的隐藏线索。

What I know so far is that obj = 1, 2, 7 is equivalent to obj.operator=(1).operator,(2).operator,(7);

没错。请注意 operator, 在这个任务中几乎是 operator= 的同义词:

obj.operator=(1).operator=(2).operator=(7);

所以,这只是实施这个技巧的问题:

Sample& Sample::operator,(const int& val)
{
    // simply reuse the assignment operator
    *this = val;

    // associativity of comma operator will take care of the rest
    return *this;
}

实施 operator= 由您决定。

那你可以做

obj = 1, 2, 7;

我制作了一个与您的示例类似的小型工作代码:Live Demo.

编辑:

根据 Jarod 的评论,建议更合理地重载这些运算符,您可以通过这种方式重载 operator= (clear + push_back):

Sample& Sample::operator=(const int& val)
{
    arr[0] = val;
    length = 1;
    return *this;
}

operator,这样(push_back):

Sample& Sample::operator,(const int& val)
{
    // append the value to arr
    arr[length] = val;
    ++length;

    // associativity of comma operator will take care of the rest
    return *this;
}

把这个想法放在一起:Demo 2