Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simplify this addition interface?

Tags:

c++

I've built this interface for things that are addable with themselves, and it's pretty nice so far. However, I have to do *a+*b to add things, and when you have to do *(*a+*b)+*a, using it gets pretty annoying pretty fast. Is there a way to modify it to be simpler to use?

#include <iostream>
#include <memory>
#include <set>
#include <map>
#include <string>


class iResult
{
public:
    virtual std::shared_ptr<iResult> operator+(const iResult& rhs) const = 0 ;
    virtual std::string print() const = 0;
};


class intResult : public iResult
{
public:
    intResult(int b) : num(b) {};
    std::string print() const
    {
        return std::to_string(num);
    }

    std::shared_ptr<iResult> operator+(const iResult& rhs) const 
    {
        return std::make_shared<intResult>(num + dynamic_cast<const intResult&>(rhs).num);
    }
private:
    const int num;
};



int main()
{
    std::shared_ptr<iResult> a = std::make_shared<intResult>(3);
    std::shared_ptr<iResult> b = std::make_shared<intResult>(4);
    std::shared_ptr<iResult> c = *a + *b;
    std::shared_ptr<iResult> z = *(*a + *b) + *a; //Gross!
    std::cout << c->print() << std::endl;
    std::cout << z->print() << std::endl;
    return 0;
}
like image 265
Carbon Avatar asked Sep 14 '26 17:09

Carbon


1 Answers

Just add another layer of abstraction. Since your operator+ wants an const iResult& you can add another overload that takes const std::shared_ptr<iResult>& and does all the dereferencing in it. If you add

std::shared_ptr<iResult> operator +(const std::shared_ptr<iResult>& rhs, const std::shared_ptr<iResult>& lhs)
{
    return *rhs + *lhs;
}

to the global space then in main()

std::shared_ptr<iResult> c = *a + *b;
std::shared_ptr<iResult> z = *(*a + *b) + *a; //Gross!

becomes

std::shared_ptr<iResult> c = a + b;
std::shared_ptr<iResult> z = a + b + a; //Nice!

Live Example

like image 200
NathanOliver Avatar answered Sep 16 '26 06:09

NathanOliver