Question

Here's the ideone code: http://ideone.com/Qp8Eqg

My question is, is it possible to force a conversion based on the lvalue alone? For example,

[Seconds] s = 2_h + 60_s;
cout <<s.getSeconds()<<endl;

Obviously, I would have to write something like 2_h.toSeconds(), but that would be too verbose and doesn't achieve the idea.

Was it helpful?

Solution

To allow this (which is more likely your question than what you wrote, correct me if I'm wrong):

Seconds s = 2_h;

the following would work: Add operator Seconds() const to class Hours:

class Hours {
    unsigned long long _hours;
public:
    Hours(unsigned long long hours) : _hours(hours) { }

    operator Seconds() const;

    unsigned long long getHours() const {
        return this->_hours;
    }
};

and define it after class Seconds:

Hours::operator Seconds() const { return this->_hours * 3600; }

OTHER TIPS

As already noted in the answer given you need to have the operator Seconds () implemented to allow automatic conversion from Hours to Seconds. With this operator in place you can also simplify operator+. And to improve run-time you can also throw in some constexpr to have values evaluated at compile time.

#include <iostream>

class Seconds {
    public:
        constexpr Seconds(const Seconds& other) : seconds_(other.seconds_) {}
        constexpr Seconds(unsigned long long seconds) : seconds_(seconds) {}

        Seconds& operator=(const Seconds& other) {
            seconds_  = other.seconds_;
            return *this;
        }

        constexpr unsigned long long value() const {
            return this->seconds_;
        }

    private:
        unsigned long long seconds_;
};


class Hours {
    public:
        constexpr Hours(const Hours& other) : hours_(other.hours_) {}
        constexpr Hours(unsigned long long hours) : hours_(hours) {}

        Hours& operator=(const Hours& other) {
            hours_ = other.hours_;
            return *this;
        }

        unsigned long long value() const {
            return this->hours_;
        }

        operator Seconds () const { return Seconds(hours_*60*60); }
    private:
        unsigned long long hours_;
};


constexpr Seconds operator+(const Seconds& lhs, const Seconds& rhs) 
{
    return Seconds(lhs.value()+rhs.value());
}

constexpr Hours operator "" _h(unsigned long long hours) {
    return Hours(hours);
}

constexpr Seconds operator "" _s(unsigned long long seconds) {
    return Seconds(seconds);
}


int main() {
    using namespace std;

    Seconds s = 1_h + 10_s;
    cout <<s.value()<<endl;
    s = 2_h + 60_s;
    cout <<s.value()<<endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top