5 May 2007

Templated Methods

I wasn't aware that one can do something like this in C++:

Ptr< MyClass > myObj = factory->Create< MyClass >(MyClass::RTTI);

I only saw this in some XNA code examples, and took it for something that's specific to C# generics. Turns out it works in C++ as well. When working with smart pointers, this is pretty nice, because automatic pointer casting doesn't work between smart pointers of different types. So the alternative to the above code would be (assuming the Create() method returns a Ptr<>):

Ptr< MyClass > myObj = (MyClass*) factory->Create().get();

Pretty ugly with the required cast and the .get() method...

In some cases, templated method calls may also save an implicit hidden construction of a smart pointer object. I'm not completely sold yet however:

The bad:
  • it seems to be an unusual construct, haven't seen this yet in C++ code, maybe some compilers choke on this
  • templated methods MUST be inline, and cannot be virtual, so it maybe that the mechanism cannot be used everywhere where it would make sense
On the other hand:
  • it's a perfect fit for smart pointers
  • it may produce more efficient code (and should never produce less efficient code)
I'll have to ponder over this for a little while... I feel that the underlying problem is that a smart pointer doesn't provide a cast-operator to a different (compatible) pointer type... maybe with the newfound wisdom there is a way to add a templated cast operator to the smart pointer class itself, which would make the raw pointer casts and calling the .get() method unnecessary, but this would still require implicit object construction at method calls in some cases.

Nonetheless C++ never stops to amaze me, in some sort of scary way...

2 comments:

Jules said...

"it seems to be an unusual construct, haven't seen this yet in C++ code, maybe some compilers choke on this"

It's standard C++, I thought you should know this. It'll will make the pondering easier on the mind ;-).

Floh said...

Sure it's standard C++, but most C++ compilers still aren't 100% ISO C++ compliant as far as I know...