Search code examples
c++templatescastingc++14return-value-optimization

Custom static cast function template in C++14


I've written such a template function for static casting as kind of an exercise:

template<typename cT, typename T>
inline constexpr cT sCast(T carg) {
    return static_cast<cT>(carg);
}

I just didn't want to type static_cast<someT>(some_obj) all the time, so I challenged myself to write my own template function with a shorter name. However, I knew I can do something much easier in one line of code:

#define sCast static_cast
   ...
sCast<someT>(some_obj);

But as I said, I wanted to design a function template just for exercise.

Now my question is: is this function template as efficient as possible and if not, how can it be better? Will template functions meet conditions of RVO optimalization? Or maybe I'm just a perfectionist and such ideas are waste of time?


Solution

  • this template is not as efficient as just using static_cast. The reason is that the function has to be explicitly pushed onto the stack, and its arguments have to be cleaned up afterwards. Most compilers will inline it (==> it is as if you wrote static_cast instead of the function from above), but if your compiler chooses to not inline it, it will impact your performance (even though just slightly, and its unlikely anyone would ever notice that)