0

Is it possible to have an array with int values and int references?

Is there any other way to have an array arr such that when you print arr[1] it always prints the value of arr[0] (without having to update arr[1] when arr[0] is modified) ?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 4
    An array has to contain elements of the same type. `int` and `int&` are different, so no – kmdreko May 13 '16 at 14:46
  • What are you intending to do? – Mona the Monad May 13 '16 at 14:46
  • 9
    This sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please detail your actual problem. – TartanLlama May 13 '16 at 14:47
  • 10
    You can't have an array of **any** references. You can have an array of reference wrappers, which are pointers in disguise. – SergeyA May 13 '16 at 14:47
  • boost::variant would do this. – Richard Hodges May 13 '16 at 15:00
  • Smells like XY. Why do you want to do this? – Karoly Horvath May 13 '16 at 15:06
  • Slightly tricky. You could define an array of integers and static cast the members. Problem is, an address on a 64 bit system is, well 64 bit and standard integer only 32 bit. Otherwise define your own class and overload the [] operator. Nevertheless even though this should accomplish what you want, I do not find it particularly useful – Mohammed Li May 13 '16 at 15:10

1 Answers1

0

No, but you may have such a desired array:

#include <iostream>
using namespace std;

class CIntRef
{
public:
    CIntRef(const int & ref) : ref(ref) {}
    operator const int &() { return ref; }
    const int& operator=(const int &i) {
        const_cast<int&>(ref) = i;
        return ref;
    }
private:
    const int & ref;
};

int main()
{
    int a = 2;
    CIntRef arr[] = { a, a, 0, 1 };
    cout << arr[1] << endl; // <-- prints: 2
    arr[0] = 3;
    cout << arr[1] << endl; // <-- prints: 3
    return 0;
}
Community
  • 1
  • 1
someOne
  • 1,975
  • 2
  • 14
  • 20