Amumu
Amumu

Reputation: 18552

Cast to an unknown template type

So I saw code like this:

template<class T>
T* safe_ptr_cast(Message& msg) {
    assert(msg.header()->size() == T::size());
    return msg.header()->size() == T::size ? reinterpret_cast<T*>(msg.dest()) : NULL;
}

How can the msg be cast? Generally, the parameter list needs to have a parameter type T in order to let the function recognize what type to cast. However, in this case, the parameter type is explicitly stated. Does this mean reinterpret_cast will cast the Message type to its corresponding subclasses?

For example, the Message class has a subclass RequestMessage with some additional members, a subclass ResponseMessage with some additional members as well. I assume the size of RequestMessage is 50 bytes, and ResponseMessage is 100 bytes. Upon casting, if the msg object has 50 bytes, it will be cast to RequestMessage, and if the msg object has 100 bytes, it will be cast to ResponseMessage. Is this correct?

Upvotes: 0

Views: 680

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63704

Since the template type can't be determined from the parameter being passed, the compiler won't attempt to determine the template parameter.

It must be explicitly specified at the call site.

safe_ptr_cast<TheType>(msg);

Upvotes: 1

Sumudu Fernando
Sumudu Fernando

Reputation: 1763

I'm not totally sure I understand the question, but I think you're asking how does the compiler know what type you want to cast to, because the parameter is always a Message&

It does not automagically select based on the size: the assert is there to catch programmer errors.

You have to manually specify what type you want when you call the function: safe_ptr_cast<RequestMessage>(msg)

EDIT: I had meant to comment that you may want to look at virtual functions because they might be more appropriate (at least in one situation I can imagine where you'd have a function like this one).

Upvotes: 2

Related Questions