vendredi 23 juillet 2021

Extending c++ base types?

Currently I'm attempting to write a class that can create a wrapper around a c++ primitive type to allow me to extend it(ie. add some kind of check to the constructer). As of right now this is as far as I have gotten

template <typename T>
class wrapper {
    protected:
        using base_type = T;
        T _value;
    public:
        wrapper(T val = T{}) : _value(val) {}

        operator T& () { return _value; }
        operator const T& () const { return _value; }

        T* operator &() { return &_value; }
        const T* operator &() const { return &_value; }

        T* operator ->() { return &_value; }
        const T* operator ->() const { return &_value; }

        static std::string getTypeID() { return typeid(base_type); }    
};

my goal is that I can do something akin to the following:

typedef wrapper<int> MyInt;
typedef wrapper<Poco::UInt32> WrappedPocoInt32;
MyInt testValue = 5;
WrappedPocoInt32 pocoValue = testValue;

std::cout << std::to_string(pocoValue) << std::endl;

if(pocoValue <= 10) {
    pocoValue++;
}
// etc...

basically I want to have access to all the normal functionality of the type along side custom modifications that I can make to it, say

class MyInt : public wrapper<int> {
    MyInt(int val) {
        if(val >= 10) {
            this->_value = val;
        } else {
            // error
        }
    }

};

MyInt myValue = 5;

Aucun commentaire:

Enregistrer un commentaire