dtech
dtech

Reputation: 49319

Automatic casting of template object to template pointer in c++

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?

Upvotes: 0

Views: 418

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

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.

Upvotes: 4

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76856

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.

Upvotes: 2

Related Questions