Despite you can write a binary number in C++14 like:
int number =0b0001'0101; // ==21
here comes a famous example with a self-made implementation for binary numbers:
Note: The whole template expanding program is running at compile time.
template<char FIRST,char... REST >structbinary{static_assert( FIRST =='0'|| FIRST =='1',"invalid binary digit");enum{ value =(( FIRST -'0')<<sizeof...(REST))+ binary<REST...>::value };};template<>structbinary<'0'>{enum{ value =0};};template<>structbinary<'1'>{enum{ value =1};};// raw literal operatortemplate<char... LITERAL >inlineconstexprunsignedintoperator""_b(){return binary<LITERAL...>::value ;}// raw literal operatortemplate<char... LITERAL >inlineconstexprunsignedintoperator""_B(){return binary<LITERAL...>::value ;}#include<iostream>intmain(){
std::cout <<10101_B <<", "<<011011000111_b <<'\n';// prints 21, 1735}
User-defined literals with long double values
#include<iostream>longdoubleoperator""_km(longdouble val){return val *1000.0;}longdoubleoperator""_mi(longdouble val){return val *1609.344;}intmain(){
std::cout <<"3 km = "<<3.0_km <<" m\n";
std::cout <<"3 mi = "<<3.0_mi <<" m\n";return0;}
The output of this program is the following:
3 km =3000 m
3 mi =4828.03 m
Standard user-defined literals for duration
Those following duration user literals are declared in the namespacestd::literals::chrono_literals, where both literals and chrono_literals are inline namespaces(opens new window). Access to these operators can be gained with using namespace std::literals, using namespace std::chrono_literals, and using namespace std::literals::chrono_literals.
Those following string user literals are declared in the namespacestd::literals::string_literals, where both literals and string_literals are inline namespaces(opens new window). Access to these operators can be gained with using namespace std::literals, using namespace std::string_literals, and using namespace std::literals::string_literals.
std::string s1 ="foo\0\0bar";// constructor from C-string: results in "foo"s
std::string s2 ="foo\0\0bar"s;// That string contains 2 '\0' in its middle
Standard user-defined literals for complex
Those following complex user literals are declared in the namespacestd::literals::complex_literals, where both literals and complex_literals are inline namespaces(opens new window). Access to these operators can be gained with using namespace std::literals, using namespace std::complex_literals, and using namespace std::literals::complex_literals.