Sign in to follow this  

How is cast<T>() registered?

This topic is 832 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Just what it says in the title. I know you can't register template methods on objects, but it's recently occurred to me that cast appears to use a templated function. Is that something that's built into the language, or can it be repeated in user code?

 

I'm working on a few classes that expose reflection to the scripting language, and currently I've got it set up like this:

 

  • I have a Type class, which has no default factory. It requires a parameter of type __typeof.
  • I have a Typeof class, which is registered with the engine as both __typeof and typeof<T>.
  • typeof<T> is implicitly convertable to __typeof.
  • __typeof has no factory defined at all, so it can only be created from an instance of typeof<T>.

It's a convoluted setup, but ultimately it allows me to do this:

Type myType(typeof<MyClass>())

What I'm wondering now is whether I can make a function that behaves in the same way as cast<T>(), with the end result being a syntax that looks like this:

Type myType = typeof<MyClass>();

Of course, the best possible result would be to mimic C# syntax exactly, but I don't think that's possible;

Type myType = typeof(MyClass);

Share this post


Link to post
Share on other sites

cast<T>() is not registered. This is a built-in function, and serves the same purpose as dynamic_cast<T>() in C++.

 

You can implement the opImplConv overload in the typeof<T>() class to allow it to be implicitly converted to the Type object.

 

You may want to take a look at this post. cvet has already implemented and shared code that does exactly what you want.

Share this post


Link to post
Share on other sites

I assumed that would be the case. The implicit cast trick is a good one (and I actually realized I could do it while writing this post), the only drawback is that you have to assign it before you can use the properties or methods of the Type class...though I suppose I could register the same members to both types.

 

That post looks great! I'll definitely check his code out. Thanks for the reply.

Share this post


Link to post
Share on other sites

This topic is 832 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this