C ++ Templates: Inline Code and Compiler Optimization

Can we assume that the following code, optimized and built in by the compiler, will remove the branch needed to evaluate the triple operation? Or, with most major compilers, would it be wiser to split the method below into two separate methods to avoid a branch?

/*! \brief this method returns the cos of an angle. User can specify if it is * in degrees or radians. */ template <typename T, angle_mode AM> T cos(const T &angle) { return (AM == radians) ? std::cos(angle) : std::cos(degrees_to_radians(angle)); } 
+4
source share
1 answer

Yes, this should always be optimized.

Even if it is not, I feel that the cost of std::cos greatly outshine the cost of the conditional.

If for some reason it is not optimized, use specialized template specialization to force the branch at compile time.

+4
source

Source: https://habr.com/ru/post/1486358/


All Articles