I am trying to implement a reference - like class called Ref. Currently, the class contains a pointer to my object. The class should behave like a natural object. The skeleton of the class looks like this:
template typename<T>
class Ref {
public:
T* value;
// Constructors - not really important
}
I would like that the user could use the class as follows:
void foo(int x) {// whatever is there doesn't really matter}
int main() {
auto x = Ref<int>(5) // Hopefully with c++20 the user would just write Ref(5)
foo(x); // Should be converted to foo(*(x.value))
x += 5; // Should be converted to *(x.value) += 5
}
The pattern here is that any function foo applied to a Ref object would be converted to foo(*(x.value)). How can this be done?? Therefore, the user would be able to use a Ref object just like a normal object.
I know one possible solution:
template typename<T>
class Ref {
public:
T* value;
template <typename R>
R apply(R (*foo) (ref<T>)) {return foo(*value);}
}
However, now the user has to type
auto x = Ref<int>(5);
x.apply(foo);
Which I don't want at all; I want my Ref object to behave like a natural object.
Why don't I use references instead : I want to be able to make an array of Ref objects. Why don't I use pointers instead: I want to add additional constraints to the Ref class to make it safer than pointers.
This is not the only use case I can think of, another case where overloading every possible function is desirable is when you want to implement an array of objects of type T class which behaves like this:
void foo(int x) {///Whatever is here}
int main()
{
auto y = CustomArray<int>{1,2,3,4};
foo(y); // applies foo to every element of y (element - wise)
}
Note : I am aware that this is probably very difficult / impossible to do in pure c++. However, I am open to some solutions which take in a file where the writer writes foo(x) (x is a Ref object here) and which converts this to a c++ file in which you have x.apply(foo); (like a sort of transpiler).