user81993
user81993

Reputation: 6609

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

I have several structures that go similar to 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.. Essentially they are just interpretations of any of the base classes and defining all the operators and such for them is really tedious. The interpretation functions(such as "parse" in the example) are important because I use them all over the UI. I know I could create interpretation functions as standalone thingies like this

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

but referring to those functions as class methods makes for a much nicer looking code.

If only there was a way to "typedef Int64_t Time64" and then expand the Time64 "class" by adding some methods to it..

Is there any way to achieve what I'm trying to do easier than what I got going on right now?

Upvotes: 4

Views: 305

Answers (2)

Moby Disk
Moby Disk

Reputation: 3861

Here is how to do it without boost:

You need to make your structure implicitly convertable to the underlying type, like CoffeeandCode said. That is a big part 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 convertible to an integer, it can often be mistakenly used as a pointer, or it can be unclear what it will do when passed to printf() or cout.

Upvotes: 1

Barry
Barry

Reputation: 303147

I think you want BOOST_STRONG_TYPEDEF. You can't inherit from int, as int is not a class type, but you could do:

BOOST_STRONG_TYPEDEF(int64_t, Time64Base);

struct Time64 : Time64Base {
    std::string Parse() { ... }
};

Upvotes: 4

Related Questions