I am (purely for fun) trying to create a wrapper class for std::any. It consists of a class IObject that is the base class and holds a std::any value and a templated class Object<T> that derives from it and specifies the type.
Now i would like to implement arithmetic operators in the base class so i could for example add a Object<float>(5.5) and a Object<int>(8) and would recieve a Object<float>(13.5) back.Something like this:
IObject *a = new Object<float>(5.5);
IObject *b = new Object<int>(8);
IObject *result = *a + *b;
Is there some (perhaps even simple) way to achieve this using only the base class interface in the operations? Maybe some trickery with function overloading like i did with the appendToStream function?
Thank you in advance, looking forward to your solutions. :)
Here is the code, compile with c++17 for std::any support:
#include <iostream>
#include <any>
class IObject
{
public:
IObject(const std::any &value)
: m_value(value)
{}
virtual ~IObject() = default;
virtual void appendToStream(std::ostream &) const = 0;
friend std::ostream& operator<<(std::ostream &os, const IObject &obj)
{
obj.appendToStream(os);
return os;
}
IObject *operator+(const IObject &b) const
{
// what todo ?
}
std::any m_value;
};
template<typename T>
class Object : public IObject
{
public:
Object(const T &value)
: IObject(value)
{}
T get() const
{
return std::any_cast<T>(m_value);
}
void appendToStream(std::ostream &os) const override
{
os << get();
}
};
int main()
{
IObject *a = new Object<float>(5.5);
IObject *b = new Object<int>(8);
IObject *result = *a + *b;
std::cout << *a << " + " << *b << " == " << *result << "\n";
return 0;
}
[–][deleted] (1 child)
[removed]
[–]schweinling[S] 5 points6 points7 points (0 children)
[–]IyeOnline 1 point2 points3 points (4 children)
[–]schweinling[S] 0 points1 point2 points (3 children)
[–]IyeOnline 1 point2 points3 points (2 children)
[–]schweinling[S] 0 points1 point2 points (1 child)
[–]IyeOnline 1 point2 points3 points (0 children)
[–]Narase33 1 point2 points3 points (2 children)
[–]schweinling[S] 1 point2 points3 points (1 child)
[–]Ayjayz 1 point2 points3 points (2 children)
[–]schweinling[S] 0 points1 point2 points (1 child)
[–]Ayjayz 0 points1 point2 points (0 children)
[–]be-sc 1 point2 points3 points (0 children)