Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload `unsigned` specifier for classes

Tags:

c++

I'm trying to define my own datatype (called sfloat) that's similar to a float, but uses a different number of mantissa bits and exponential bits to better suit my data range and precision. The goal is to define a new datatype that can replace the float in already existing applications. Everything's working out so far, except that I have been unable to override or define the unsigned operator such that

unsigned sfloat(3.141527)

would return the unsigned version of this class, usfloat(3.141527).

It seems like the unsigned specifier might be able to be overloaded since VS intellisense is not complaining in the header file:

sfloat::sfloat(float f) { m_data = get16bit(f); }
operator unsigned() { /*Do stuff here */ };

But it's not working in declaration and initialization:

unsigned sfloat myPi= 3.141527; // Error: expected a ';'

I don't even know if this is possible to do in C++, and I'm curious if anybody has done this before?

like image 251
John Phu Nguyen Avatar asked Jun 17 '13 18:06

John Phu Nguyen


1 Answers

Due to C++ default-int for signedness, operator unsigned () is just a syntactic shorthand for operator unsigned int (). User-defined types cannot be declared signed or unsigned.

like image 114
Angew is no longer proud of SO Avatar answered Oct 12 '22 23:10

Angew is no longer proud of SO