如何在不使用abs()或循环(if/else)的情况下构建Absolute函数,只需使用运算符(C++)即可



如果您能建议并分享如何在不使用abs((或循环(if/else(的情况下构建Absolute函数,只需使用运算符(C++(

template<typename N>
N abs(const N& n)
{
const N arr[2] = {n, -n};
return arr[n < 0];
}

是一种方式。它也不会倾倒管道。

使用C++20概念还有另一种方法:

#include <iostream>
#include <concepts>

auto abs( std::integral auto num )
{
return num < 0 ? -num : num;
}
int main( )
{
std::cout << abs( -4 ) << ' ' << abs( 12345 ) << 'n';
}

最新更新