Last active
July 21, 2020 08:13
-
-
Save kjk/fe86de3b2a3f5071478225350e1126ac to your computer and use it in GitHub Desktop.
Example for https://essential-cpp.programming-books.io/user-defined-literals-d3696e4f87894401af6c2f073d356228 (made with https://codeeval.dev)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template< char FIRST, char... REST > struct binary | |
{ | |
static_assert( FIRST == '0' || FIRST == '1', "invalid binary digit" ) ; | |
enum { value = ( ( FIRST - '0' ) << sizeof...(REST) ) + binary<REST...>::value } ; | |
}; | |
template<> struct binary<'0'> { enum { value = 0 } ; }; | |
template<> struct binary<'1'> { enum { value = 1 } ; }; | |
// raw literal operator | |
template< char... LITERAL > inline | |
constexpr unsigned int operator "" _b() { return binary<LITERAL...>::value ; } | |
// raw literal operator | |
template< char... LITERAL > inline | |
constexpr unsigned int operator "" _B() { return binary<LITERAL...>::value ; } | |
int main() | |
{ | |
// 10101 in binary is 21 | |
std::cout << 10101_B << "\n"; | |
// 011011000111 in binary is 1735 | |
std::cout << 011011000111_b << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment