0

I have a URes class which contains a single pointer to <T>, with indirection operators -> and * overloaded so I can use the instance as a pointer directly.

However I also want to be able to pass my URes instance to functions that normally take the pointer inside the URes instance.

How do I make it so that when my URes instance object is passed to a function it is automatically cast to the pointer it contains?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
dtech
  • 47,916
  • 17
  • 112
  • 190

2 Answers2

4

The same way that you create any outbound conversion: by declaring and defining an operator.

In this case, you want a member operator T*.

Example:

template <typename T>
struct Foo {
   operator T*() {
      return 0;
   }
};

void bar(int* p) {}

int main() {
   Foo<int> f;
   bar(f);
}

However, I'd recommend avoiding this and implementing a member T* get() instead. It should be an explicit step for a calling scope to obtain a pointer from your object.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

You can do that by providing a conversion operator from that class to the pointer-type:

class Foo {
public:
    operator int() const { // enables implicit conversion from Foo to int
    }
};

Note that such implicit conversion can introduce unexpected behavior.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283