From cppreference.com
Defined in header
template<classT,classS>constexprTshr(Tx,Ss)noexcept;(since C++29)Returns ⌊x · 2-s
⌋ rounded towards negative infinity, and truncated to fit into T.
Parameters
x - value of unsigned integer type s - number of positions to shift Return value
⌊x · 2-s
⌋ truncated to the result type.
Notes
Unlike the >> operator, std::shr never has undefined behavior. Shifting takes place as if by shifting to the right by a single bit s times, or shifting to the left by a single bit -s times if s is negative, except that -s cannot overflow.
macroValueStdFeature
(C++29)
Possible implementation
template<classT,classS>// TODO: constraintsconstexprTshr(Tx,Ss)noexcept{constexprautowidth=S(std::numeric_limits<std::make_unsigned_t<T>>::digits);ifconstexpr(std::is_signed_v<S>){if(s<0)returns<=-width?T(0):x<<-s;}returns>=width?T(x<0?-1:0):x>>s;}Example
Run this code
#include<bit>#include<concepts>#include<cstdint>#include<limits>template<std::unsigned_integralT>constexprboolis_set(Tbits,intbit_num)noexcept{#if (__cpp_lib_bitops >= 202606L)// Never undefined.returnstd::shr(bits,bit_num)&1;#else// Requires special cases to guard against overlong// shifts, otherwise the behavior is undefined.if(std::numeric_limits<T>::digits<bit_num)returnfalse;return(bits>>bit_num)&1;#endif}static_assert(is_set(0b101U,0));static_assert(!is_set(0b101U,1));static_assert(is_set(0b101U,2));static_assert(!is_set(0b101U,69));// well formed#if (__cpp_lib_bitops >= 202606L)static_assert(std::shr(std::uint8_t(0b0011),-2)==0b1100);// negative shift is OK#endifintmain(){}See also
(C++29)
shifts to the left without the possibility of undefined behavior
(function template)
(C++20)
computes the result of bitwise left-rotation
(function template)
(C++20)
computes the result of bitwise right-rotation
(function template)