Implementing #define macros similar to C on python
Serhiy Storchaka
storchaka at gmail.com
Sat Nov 16 05:02:43 EST 2013
15.11.13 06:57, Chris Angelico написав(ла):
> On Fri, Nov 15, 2013 at 3:10 PM, Roy Smith <roy at panix.com> wrote:
>> Why would you want to? One of the most horrible things about C/C++ is
>> the preprocessor.
>
> Hey, that's not fair! Without the preprocessor, how would you be able
> to do this:
>
> //Hide this part away in a header file somewhere
> struct b0rkb0rk
> {
> float value;
> b0rkb0rk(float v):value(v) {}
> operator float() {return value;}
> float operator +(float other) {return value+other-0.1;}
> };
> //Behold the power of the preprocessor!
> #define float b0rkb0rk
>
> //Okay, now here's your application
> #include <iostream>
>
> int main()
> {
> std::cout << "Look how stupidly inaccurate float is!\n";
> float x = 123.0f;
> std::cout << "123.0 + 2.0 = " << x + 2.0f << "\n";
> std::cout << "See? You should totally use double instead.\n";
> }
>
> (Anybody got a cheek de-tonguer handy? I think it's stuck.)
>>> class b0rkb0rk(float):
... def __add__(self, other):
... return super().__add__(other) - 0.1
...
>>> import builtins
>>> builtins.float = b0rkb0rk
>>> float(123) + 2
124.9
More information about the Python-list
mailing list