What exactly is std :: labs () for?

I read about the std::abs() function when viewing cppreference .

On this page, I also saw the std::labs() function. Which has the same prototype as one of the std::abs() overloads (one for long ).

 long abs( long n ); long labs( long n ); 

and

 long long abs( long long n ); long long llabs( long long n ); 

So,

  • What exactly does std::labs() do?
  • Where and when do I use std::labs() ?
  • What is the difference between std::abs() and std::labs() ?
+43
c ++ c prototype c ++ 11
Sep 27 '17 at 6:42 on
source share
1 answer

C ++ 11 was when std::labs and std::llabs were added. This was part of a partial synchronization with the C ++ standard library with the C99 standard library.

In C ++ code, this really is not necessary, because we have had an overload of long std::abs since forever. But if you have C code (which coincidentally also compiles using the C ++ compiler) and it uses labs , you can create it using the compiler and the standard C ++ 11 library.




In retrospect, there is one very useful use case for these functions. And then the attempt to use std::abs ambiguous. For example:

 template<typename T> T run_func(T (&f)(T)) { return f({}); } 

Then an attempt to call run_func(std::abs); poorly formed. We need to either explicitly specify the template argument, or apply std::abs to the appropriate type. On the other hand, run_func(std::labs); not ambiguous and not too detailed.

However, not too helpful.

+58
Sep 27 '17 at 6:45
source share



All Articles