Created
November 27, 2012 12:23
-
-
Save lichray/4153963 to your computer and use it in GitHub Desktop.
User-defined binary literal in C++11
This file contains hidden or 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> | |
| // http://stackoverflow.com/questions/537303/binary-literals | |
| template<char... digits> | |
| struct conv2bin; | |
| template <char... digits> | |
| constexpr int operator"" _b() { | |
| return conv2bin<digits...>::value; | |
| } | |
| template <> | |
| constexpr int operator"" _b<'0'>() { | |
| return 0; | |
| } | |
| template <> | |
| constexpr int operator"" _b<'1'>() { | |
| return 1; | |
| } | |
| template<char high, char... digits> | |
| struct conv2bin<high, digits...> { | |
| static constexpr int value = operator"" _b<high>() << | |
| sizeof...(digits) ^ conv2bin<digits...>::value; | |
| }; | |
| template<char high> | |
| struct conv2bin<high> { | |
| static constexpr int value = operator"" _b<high>(); | |
| }; | |
| int main() { | |
| std::cout << 0_b << std::endl; | |
| std::cout << 101_b << std::endl; | |
| std::cout << 000111101_b << std::endl; | |
| std::cout << 11111111111111111111111111111111_b << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
I referenced your work in my answer to "How to get smallest variable with C++11 user defined literals" here: https://stackoverflow.com/a/53702658/1353336