Is there a way to “inherit” a base type such as int?

I have several structures that look like this:

struct Time64 { int64_t Milliseconds; Time64 operator+(const Time64& right) { return Time64(Milliseconds + right.Milliseconds); } ... blah blah all the arithmetic operators for calculating with Time64 and int64_t which is assumed to represent milliseconds std::string Parse() { fancy text output } } 

And now I need to add even more of them. In essence, these are just interpretations of any of the base classes and definition of all operators, and for them it is really tiring. Interpretation functions (for example, “parsing” in the example) are important because I use them throughout the user interface. I know that I can create interpretation functions as autonomous things like this

 std::string InterpretInt64AsTimeString(const Int64_t input) {...} 

but referring to these functions, since class methods make much more beautiful code.

If there was a method of "typedef Int64_t Time64", then expand Time64 "class" by adding several methods to it.

Is there a way to achieve what I'm trying to do easier than what I just started?

+4
source share
2 answers

Here's how to do it without promotion:

You need to make your structure implicitly convertible to a base type, such as CoffeeandCode. This is much of what BOOST_STRONG_TYPEDEF does.

 struct Time64 { int64_t Milliseconds; operator int64_t &() { return Milliseconds; } }; int main(){ Time64 x; x.Milliseconds = 0; x++; std::cout << x << std::endl; } 

This can often be a dangerous approach. If something is implicitly converted to an integer, it can often be mistakenly used as a pointer, or it may not be clear what it will do when passing printf () or cout.

+1
source

I think you want BOOST_STRONG_TYPEDEF . You cannot inherit from int since int not a class type, but you can do:

 BOOST_STRONG_TYPEDEF(int64_t, Time64Base); struct Time64 : Time64Base { std::string Parse() { ... } }; 
+4
source

All Articles