Array typecast operator overloading.

Oct 21, 2020 at 2:19pm
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 Oct 21, 2020 at 2:36pm
Oct 21, 2020 at 2:22pm
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.
Oct 21, 2020 at 2:36pm
That was a typo in my question. Updated to a more concrete example.
Oct 21, 2020 at 2:53pm
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 Oct 21, 2020 at 2:59pm
Oct 21, 2020 at 2:54pm
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.