Now that we soon have user defined literals (UDL), in GCC 4.7 for example, I'm eagerly waiting for (physical) unit libraries (such as Boost.Units) using them to ease expression of literals such as 1+3i, 3m, 3meter or 13_meter. Has anybody written an extension to Boost.Units using UDL supporting this behaviour?
No one has come out with such an extension. Only gcc (and possibly IBM?) has UDL so it might be a while. I'm hoping some kind of units makes it into tr2 which is starting about now. If that happens I'm sure UDL for units will come up.
This works:
// ./bin/bin/g++ -std=c++0x -o units4 units4.cpp
#include <boost/units/unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
using namespace boost::units;
using namespace boost::units::si;
quantity<length, long double>
operator"" _m(long double x)
{ return x * meters; }
quantity<si::time, long double>
operator"" _s(long double x)
{ return x * seconds; }
int
main()
{
auto l = 66.6_m;
auto v = 2.5_m / 6.6_s;
std::cout << "l = " << l << std::endl;
std::cout << "v = " << v << std::endl;
}
I think it wouldn't be too hard to go through you favorite units and do this.
Concerning putting these in a library:
The literal operators are namespace scope functions. The competition for suffixes is going to get ugly. I would (if I were boost) have
namespace literals
{
...
}
Then Boost users can do
using boost::units::literals;
along with all the other using decls you typically use. Then you won't get clobbered by std::tr2::units for example. Similarly if you roll your own.
In my opinion there is not much gain in using literals for Boost.Units, because a more powerful syntax can still be achieved with existing capabilities.
In simple cases, looks like literals is the way to go, but soon you see that it is not very powerful.
For example, you still have to define literals for combined units, for example, how do you express 1 m/s (one meter per second)?
Currently:
auto v = 1*si::meter/si::second; // yes, it is long
but with literals?
// fake code
using namespace boost::units::literals;
auto v = 1._m_over_s; // or 1._m/si::second; or 1._m/1_s // even worst
A better solution can be achieved with existing features. And this is what I do:
namespace boost{namespace units{namespace si{ //excuse me!
namespace abbreviations{
static const length m = si::meter;
static const time s = si::second;
// ...
}
}}} // thank you!
using namespace si::abbreviations;
auto v = 1.*m/s;
In the same way you can do: auto a = 1.*m/pow<2>(s); or extend the abbreviations more if you want (e.g. static const area m2 = pow<2>(si::meter);)
What else beyond this do you want?
Maybe a combined solution could be the way
auto v = 1._m/s; // _m is literal, /s is from si::abbreviation combined with operator/
but there will be so much redundant code and the gain is minimal (replace * by _ after the number.)
One drawback of my solution is that it polutes the namespace with common one letter names. But I don't see a way around that except to add an underscore (to the beginning or the end of the abbreviation), as in 1.*m_/s_ but at least I can build real units expressions.
Related
For example, if I have:
#include <iostream>
using namespace std;
int main()
{
int b = 1;
int c = 2;
string a = "(b + c)";
cout << (4 * a) << "\n";
return 0;
}
Is it possible to have string a interpreted literally as if the code had said cout << (4 * (b + c)) << "\n";?
No. C++ is not (designed to be) an interpreted language.
Although it's theoretically possible to override operators for different types, it's very non-recommended to override operators that don't involve your own types. Defining an operator overload for std::string from the standard library may break in future. It's just a bad idea.
But, let's say you used a custom type. You could write a program that interprets the text string as a arithmetic expression. The core of such program would be a parser. It would be certainly possible, but the standard library doesn't provide such parser for you.
Furthermore, such parser wouldn't be able to make connection between the "b" in the text, and the variable b. At the point when the program is running, it has no knowledge of variable names that had been used to compile the program. You would have to specify such information using some form of data structure.
P.S. You forgot to include the header that defines std::string.
#include<string>
///...
auto a=std::to_string(b+c);
std::cout<<4*std::stoi(a)<<std::endl;
You can just use std::string and std::stoi.
I am trying to do a simple library where the object is a point on the xy-axis.
I want to be able to use literals like this:
Point a = (3,4);
where (3,4) is a point literal.
I read about user defined literals, but (as I understood) this seems to be impossible.
May be "(3,4)"_P is possible as I understand it.
However, I found on this page interesting use of user defined literals as follows:
#include <iostream>
#include <complex>
int main()
{
using namespace std::complex_literals;
std::complex<double> c = 1.0 + 1i;
std::cout << "abs" << c << " = " << abs(c) << '\n';
}
I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.
What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".
As Some programmer dude shows, the best way is to use uniform initialization.
However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.
Remember, this is just for fun, don't use this in a real code:
struct Px { int x; };
struct Py { int y; };
struct Point {
int x;
int y;
};
constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }
constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }
then you can have:
auto p = 3_px + 4_py; // p is deduced to type `Point`
Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.
As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:
auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }
auto p = (2_px, 1_py); // p is deduced to type `Point`
You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)
What you can to is to use uniform initialization doing something like
Point a = { 3, 4 }; // note the use of curly-braces
Depending on what Point is you might need to add a suitable constructor to make it work.
You have 3 options
Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);
I am writing a utility function that returns the current time in ISO format. However, I would like to be able to specify the precision:
2017-04-28T15:07:37Z //s
2017-04-28T15:07:37.035Z //ms
2017-04-28T15:07:37.035332Z //us
I have working code to do this, however, I can't seem to find a way to make it generic:
string getISOCurrentTimestamp_us()
{
char iso_buf[30];
auto now = chrono::high_resolution_clock::now();
auto s = chrono::duration_cast<chrono::seconds>(now.time_since_epoch());
time_t seconds = (time_t) s.count();
strftime(iso_buf, sizeof(iso_buf), "%FT%T", gmtime(&seconds));
string iso_timestamp(iso_buf);
auto us = chrono::duration_cast<chrono::microseconds>(now.time_since_epoch());
auto us_diff = us - chrono::duration_cast<chrono::microseconds>(s);
char buffer[8];
std::snprintf(buffer, sizeof(buffer), ".%06d", (int) us_diff.count());
iso_timestamp += string(buffer);
iso_timestamp += "Z";
return iso_timestamp;
}
As you can see, this one only returns the microsecond version. I have a separate function using chrono:milliseconds for the millisecond version. Seems like a DRY violation to have so much similar code when the only difference is the duration template parameter and the zero-padding.
Yet being able to specify the duration is tricky. I think I'm not quite understanding function templates, because I tried something like getISOCurrentTimestamp<chrono::microseconds>(), to no avail:
template <class T>
string getISOCurrentTimestamp() {
...
auto t = chrono::duration_cast<T>(now.time_since_epoch());
auto t_diff = t - chrono::duration_cast<T>(s);
}
Another problem is deducing the amount of zero padding based on T which doesn't seem trivial either (i.e. microseconds should be zero-padded up to 6, milliseconds up to 3, etc.
How can I make this ISO String function generic? Am I approaching this the wrong way?
Edit: Using #HowardHinnant's library, I was able to write a generic wrapper:
template <class Precision>
string getISOCurrentTimestamp()
{
auto now = chrono::system_clock::now();
return date::format("%FT%TZ", date::floor<Precision>(now));
}
Invoked using:
string timestamp = getISOCurrentTimestamp<chrono::seconds>()
This free, open-source, header-only library does this by adjusting the precision of the chrono::time_point that is input into the format function. Feel free to inspect the code to see how this is done. I think you'll be especially interested in decimal_format_seconds which is responsible for computing how many fractional decimal digits to output (if any). Or feel free to just use this code.
Here is what using it looks like:
#include "date.h"
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
using namespace date;
system_clock::time_point now = sys_days{2017_y/04/28} + 15h + 7min + 37s + 35332us;
cout << format("%FT%TZ\n", floor<seconds>(now));
cout << format("%FT%TZ\n", floor<milliseconds>(now));
cout << format("%FT%TZ\n", floor<microseconds>(now));
}
with the output:
2017-04-28T15:07:37Z
2017-04-28T15:07:37.035Z
2017-04-28T15:07:37.035332Z
I need pi (3.1415...) in arbitrary (but fixed) precision in boost::multiprecision.
The constants in boost::math::constants are only defined up to a fixed number of digits, as pointed out in this answer, so I need to compute it by myself.
Because I'm using this number often and with a very large number of digits, I would like to compute it in runtime only once. what would be a simple yet fast way to have it?
I thought using
typedef number<cpp_dec_float<PRECISION> > mpfloat; // PRECISION is compile time.
const int PI = atan(mpfloat(1))*4;
but I'm not sure this is a common idiom for it.
In c++14 you can use a template variable (http://en.cppreference.com/w/cpp/language/variable_template).
Note that you can already have what you want by including
#include <boost/multiprecision/detail/default_ops.hpp>
That header ends up including constants.hpp which defines template <class T> const T& get_constant_pi().
This is the c++03 idiom for template variables already (as it stores a function-local static result value).
calc_pi has the first 1100 digits hardcoded, and the rest is calculated via optimized formulae if required.
Demo with 50 and 5000 digits:
Live On Coliru (c++14)
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/detail/default_ops.hpp>
#include <boost/multiprecision/number.hpp>
#include <iostream>
namespace {
namespace bmp = boost::multiprecision;
template <int N> bmp::number<bmp::cpp_dec_float<N> > const my_const_pi
= bmp::default_ops::get_constant_pi<bmp::cpp_dec_float<N> >();
}
int main() {
std::cout << std::setprecision(50) << my_const_pi<50> << "\n";
std::cout << std::setprecision(5000) << my_const_pi<5000> << "\n";
}
Prints
3.1415926535897932384626433832795028841971693993751
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632788659361533818279682303019520353018529689957736225994138912497217752834791315155748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035637076601047101819429555961989467678374494482553797747268471040475346462080466842590694912933136770289891521047521620569660240580381501935112533824300355876402474964732639141992726042699227967823547816360093417216412199245863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850222106611863067442786220391949450471237137869609563643719172874677646575739624138908658326459958133904780275900994657640789512694683983525957098258226205224894077267194782684826014769909026401363944374553050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382686838689427741559918559252459539594310499725246808459872736446958486538367362226260991246080512438843904512441365497627807977156914359977001296160894416948685558484063534220722258284886481584560285060168427394522674676788952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288797108931456691368672287489405601015033086179286809208747609178249385890097149096759852613655497818931297848216829989487226588048575640142704775551323796414515237462343645428584447952658678210511413547357395231134271661021359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435064302184531910484810053706146806749192781911979399520614196634287544406437451237181921799983910159195618146751426912397489409071864942319615679452080951465502252316038819301420937621378559566389377870830390697920773467221825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539057962685610055081066587969981635747363840525714591028970641401109712062804390397595156771577004203378699360072305587631763594218731251471205329281918261861258673215791984148488291644706095752706957220917567116722910981690915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398315019701651511685171437657618351556508849099898599823873455283316355076479185358932261854896321329330898570642046752590709154814165498594616371802709819943099244889575712828905923233260972997120844335732654893823911932597463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100449293215160842444859637669838952286847831235526582131449576857262433441893039686426243410773226978028073189154411010446823252716201052652272111660396665573092547110557853763466820653109896526918620564769312570586356620185581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318586769751456614068007002378776591344017127494704205622305389945613140711270004078547332699390814546646458807972708266830634328587856983052358089330657574067954571637752542021149557615814002501262285941302164715509792592309907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111790429782856475032031986915140287080859904801094121472213179476477726224142548545403321571853061422881375850430633217518297986622371721591607716692547487389866549494501146540628433663937900397692656721463853067360965712091807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862947265473642523081770367515906735023507283540567040386743513622224771589150495309844489333096340878076932599397805419341447377441842631298608099888687413260472
I'd recommend just putting the value of pi into your source code as a constant with however many digits you need.
Define it as a static within a struct.
Is there a more human-readable way for representing big numbers in the source code of an application written in C++ or C?
let's for example take the number 2,345,879,444,641 , in C or C++ if we wanted a program to return this number we would do return 2345879444641.
But this is not really readable.
In PAWN (a scripting language) for example I can do return 2_345_879_444_641 or even return 2_34_58_79_44_46_41 and these both would return the number 2,345,879,444,641.
This is much more readable for the human-eye.
Is there a C or C++ equivalent for this?
With a current compiler (C++14 or newer), you can use apostrophes, like:
auto a = 1'234'567;
If you're still stuck with C++11, you could use a user-defined literal to support something like: int i = "1_000_000"_i. The code would look something like this:
#include <iostream>
#include <string>
#include <cstdlib>
int operator "" _i (char const *in, size_t len) {
std::string input(in, len);
int pos;
while (std::string::npos != (pos=input.find_first_of("_,")))
input.erase(pos, 1);
return std::strtol(input.c_str(), NULL, 10);
}
int main() {
std::cout << "1_000_000_000"_i;
}
As I've written it, this supports underscores or commas interchangeably, so you could use one or the other, or both. For example, "1,000_000" would turn out as 1000000.
Of course, Europeans would probably prefer "." instead of "," -- if so, feel free to modify as you see fit.
With Boost.PP:
#define NUM(...) \
NUM_SEQ(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
#define NUM_SEQ(seq) \
BOOST_PP_SEQ_FOLD_LEFT(NUM_FOLD, BOOST_PP_SEQ_HEAD(seq), BOOST_PP_SEQ_TAIL(seq))
#define NUM_FOLD(_, acc, x) \
BOOST_PP_CAT(acc, x)
Usage:
NUM(123, 456, 789) // Expands to 123456789
Demo.
Another way is making an UDL. Left as an exercise (and also because it requires more code).
Here's a macro that would do it, tested on both MSVC and GCC. No reliance on Boost...
#define NUM(...) NUM_(__VA_ARGS__, , , , , , , , , , )
#define NUM_(...) NUM_MSVCHACK((__VA_ARGS__))
#define NUM_MSVCHACK(numlist_) NUM__ numlist_
#define NUM__(a1_, a2_, a3_, a4_, a5_, a6_, a7_, a8_, ...) a1_##a2_##a3_##a4_##a5_##a6_##a7_##a8_
Use it like:
int y = NUM(1,2,3,4,5,6,7,8);
int x = NUM(100,460,694);
Produces:
int y = 12345678;
int x = 100460694;
For C++1y you can now use single quote(') as a digit separator. Based on N3781: Single-Quotation-Mark as a Digit Separator which has finally been accepted. Both gcc and clang have supported this feature as part of their C++1y implementation.
So the following program (see it live for clang):
#include <iostream>
int main(){
std::cout << 2'345'879'444'641 << std::endl ;
}
will output:
2345879444641
You could use a preprocessor macro
#define BILLION (1000*1000*1000)
then code e.g. (4*BILLION) ; if you care about large power of two just ust 1<<30
PS Notice that 1e6 is a double literal (same as 1.0e6)
And you could also:
patch the GCC lexer to accept 1_234_567 notation for number literals and publish that patch for conformance with GPLv3 and free software spirit.
probably in file libpp/lex.c and/or gcc/c-family/c-lex.c and/or gcc/cpp/lex.c of future GCC 4.8, i.e. current trunk.
lobby the C & C++ standardization groups to get that accepted in future C or C++ standards.