How to use assignment operator on proxy of index operator

206 Views Asked by At

In the following code I made a template class, Its initialized in main function and I'm trying to assign char* as you can see below but It isn't working. I think the issue is in assign operator function I defined in Proxy class but I can't figure it out

#include <iostream>
using namespace std;

template <class T>
class Vector {
 public:
    T *p;

    Vector(int size) {
        p = new T[size];
    }

    class Proxy {
        Vector &a;
        int i;

     public:
        Proxy(Vector &a, int i) : a(a), i(i) {
        }

        void operator=(const T x) {
            a.p[i] = x;
        }
    };

    Proxy operator[](int i) {
        return Proxy(*this, i);
    }
};

int main() {
    Vector<char *> sv1(2);
    sv1[0] = "John";
    sv1[1] = "Doe";
}

I'm getting following error;

Error

I already tried setting parameter in assignment operator function to const, I also tried implicitly typecasting to T nothing has worked

2

There are 2 best solutions below

0
On BEST ANSWER

Try this:

using namespace std;

template <class T>
class Vector {
public:
    T* p;
    int sz;

    Vector(int size) {
        p = new T[size];
        sz = size;
    }


    template<class T>
    class Proxy {
        Vector<T>& v;
        int i;
        
    public:
        Proxy(Vector<T>& vec, int index) :v(vec),i(index) { }

        void operator= (const T val) { v.p[i] = val; }
    }; 

    Proxy<T> operator[](int index) { return Proxy<T>(*this, index); }
};

Your code will work with any basic type, (int, char, double) and pointers, but not, for example, with this:

int main() {
    Vector<char*> sv1(2);
    sv1[0] = "John";
    sv1[1] = "Doe";
}

Firstly, the Vector points to a char*, not a string literal (const char*). You'd have to cast it using a C-style cast or a const_cast. Example:

int main() {
    Vector<char*> sv1(2);
    sv1[0] = const_cast<char*>("John"); //succeeds
    sv1[1] = (char*)"Doe"; //succeeds

    sv1[0] = "John"; //fails
    sv1[1] = "Doe"; //fails
}

A string literal is always a const char* in C++.

0
On

You'll have same error writing code:

char * whatever = "something";

This code is absolutely wrong at least for string:

void operator=(const T x)
{
    a.p[i] = x;
}

Step 1: allocate buffer; Step 2: copy string to allocated buffer.

Your code is OK for primitives like char, int, etc. The following code should work:

int main() {
    Vector<char> sv1(2);
    sv1[0] = 'J';
    sv1[1] = 'D';
}