Question

Is there any possibility to shorten this declaration as I use it very often in my code

For example, I use this to cast Object to my CustomObject using

dynamic_cast/static_cast<TCustomClassName*>(SenderObject)

Is there any possibility at all to shorten this using typedef static_cast<TCustomClassName*> or something like this making sure it's possible using cast operator in typedef?

Was it helpful?

Solution

No, you cannot, and you SHOULD NOT! Do not define any macros for the cast operators, it will confuse the maintainers of your application code, and will cause havoc in your programming circles. These operators are there exactly with the reason to offer a readable way of telling the programmer, that a cast is happening here. Casts regardless that are used on an everyday basis cause confusion between programmers, so these keywords are there to help them. So, stuck to them and use them wisely. Do not revert back even to C style casting, the purpose of these operators is to offer a way of understanding what happens in the code. If you are unfamiliar with them read this: When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

OTHER TIPS

You can use templated functions instead of macros, that way you don't lose any type safety:

template<typename InputType, typename ReturnType>
void SCast(InputType Input, ReturnType &Ret)
{
    Ret = static_cast<ReturnType>(Input);
}

template<typename InputType, typename ReturnType>
void DCast(InputType Input, ReturnType &Ret)
{
    Ret = dynamic_cast<ReturnType>(Input);
}

template<typename InputType, typename ReturnType>
void RCast(InputType Input, ReturnType &Ret)
{
    Ret = reinterpret_cast<ReturnType>(Input);
}

Then you can use them like this:

TCustomClassName *cls;
SCast(SenderObject, cls); 

.

TCustomClassName *cls;
DCast(SenderObject, cls); 

.

TCustomClassName *cls;
RCast(SenderObject, cls); 

Use the keyboard shortcuts of your IDE. For example, in Eclipse, through code completion, it only takes a couple of keystrokes to enter static_cast<MyClass*>. If you need the same really often, you could even define your own keyboard macro to insert the boilerplate through one hotkey.

It is possible in this way :

auto ToUi16 = [](auto v)
{
    return static_cast<unsigned __int16>(v);
};

But it makes your code less readable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top