简体   繁体   中英

C++ Templates: Inlined code and Compiler Optimzations

Is it safe to assume that the following code when optimized and inlined by the compiler would remove the branch needed to evaluate the ternary operation? Or with most mainstream compilers would it be wiser to break the method below into two separate methods to avoid the 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));
}

Yes, that should always be optimized out.

Even if it wasn't, I have a feeling that the cost of std::cos would greatly overshadow the cost of the conditional.

If for some reason it's not being optimized, use template specialization to force the branch at compile-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM