dimanche 21 août 2016

Arithmetic type proxy

Background

I'm working on C++11 JSON mapping classes to introduce syntactically intuitive and safe objects which can serialize/deserialize itself into JSON representation.

The Question

I need to provide a good proxy for arithmetic types (mainly for int, unsigned, float, double). How to implement such thing? The first idea is to implement template class overloading all arithmetic, bitwise and comparison operators. But what overload should I write in order to avoid unnecessary work? What about cast operators? What should be return type of operator+?

Simple incomplete implementation showing the idea:

template <typename T>
class Proxy {
    T mValue;
public:
    Proxy(T value = T()) : mValue(value){}

    //Should it be defined like this...
    Proxy &operator+=(T value) {
        mValue += value;
        return *this;
    }

     //Or maybe like this...
    template <typename U>
    Proxy &operator+=(U &&value) {
        mValue += std::forward<U>(value);
        return *this;
    }

    //Should this return T or Proxy<T>?
    T operator+(T value) {
        return mValue + value;
    }


    //Is it necessary?
    operator T() const {
        return mValue;
    }

    //...
};

Alternative

But should I implement the primitive JSON fields as a proxy classes? Maybe there's a better way. For instance, I also consider making the internal value public, so instead of writing:

json.intField += 4;

the user would have to write

json.intField.value += 4;

This syntax is not as intiutive and clear as I would like it to be, but that's also an option.

Aucun commentaire:

Enregistrer un commentaire