Array typecast operator overloading.

Say I have the following (incomplete) class.

1
2
3
4
class IntArrayWrapper {
 private:
  std::array<int, 3> array;
};


Is it possible to overload the implicit typecast operator to return an int array?

Something like operator int[3]() const, which I know is invalid.
Last edited on
You need to specify the size of array (number of elements) so that the compiler can determine the size at compile time.

If you don't know the size at compile time, then use a vector instead.
That was a typo in my question. Updated to a more concrete example.
No, you can't return a C-style array from a function.
You can overload the [] operator, or return the std::array object.

Edit: I like dutch's idea better. See his post.
Last edited on
Do you mean something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <array>

class IntArray {
    std::array<int, 3> a;
public:
    operator int*() { return a.data(); }
};

void f(int *p) {
    std::cout << p[0] << '\n';
}

int main() {
    IntArray a;
    a[0] = 42;    // uses int*()
    f(a);         // uses int*()
}

Topic archived. No new replies allowed.