Question

For GCC and Clang, I can easily do this:

    // absolute value
    inline constexpr int abs(const int number)
    { return __builtin_abs(number); }
    inline constexpr long abs(const long number)
    { return __builtin_labs(number); }
    inline constexpr long long abs(const long long number)
    { return __builtin_llabs(number); }
    inline constexpr double abs(const double& number)
    { return __builtin_fabs(number); }
    inline constexpr float abs(const float& number)
    { return __builtin_fabsf(number); }
    inline constexpr long double abs(const long double& number)
    { return __builtin_fabsl(number); }

Which works like a charm. I'd like to do a similar thing for pretty much every math function, and have my code work on MSVC as well. How can I do the equivalent of the above for MSVC?

EDIT: for clarity: the question is about the __builtin_* functions, nothing else. I tried

#pragma intrinsic(abs)

but this needs a declaration of the abs function, which I would like not to have in my global namespace.

Was it helpful?

Solution

Intrinsic functions are not portable, so you'll have to manually look up the corresponding builtin function and add it to the list, and use #ifdef to switch modes.

You don't have to have to have abs in the global namespace, by the way: include <cstdlib> instead of <stdlib.h> and you will get std::abs instead.

Compilers know what their own intrinsics are, MSVC uses the /Oi switch to enable them.

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