1

I am trying to emulate boost::any for a toy language of mine, following the accepted answer from the following question,

Accessing Values in a Class Similar to boost::any

I can have,

Element e1 = 11;
Element e2 = 12.1;

now I would like to overload + so I can have,

e3 = e1 + e2;

but during run time I will not know if e1 will hold a int or a double but it will be number. So how I can I modify the const so that it also saves a variable telling me what kind of a number Element hold so I can call the correct Get method.


    template /typename Datatype/
    Element(Datatype InitialValue)
    {
        StoredValue = new ValueStorage(InitialValue);
    }

I am also doing this on a microprocessor which does not have exceptions, passes -fno-rtti to the compiler, and can not use stdlib or boost.

Community
  • 1
  • 1
Hamza Yerlikaya
  • 49,047
  • 44
  • 147
  • 241
  • Without RTTI, you can't use dynamic_cast (which is the basis of the accepted answer in your other question) – Tamás Szelei Apr 26 '11 at 13:58
  • @Tamás Szelei: What do you mean it works with static_cast if I can somehow embed type information to the object so I can use it to static cast – Hamza Yerlikaya Apr 26 '11 at 14:07
  • static_cast does not do any runtime checks. It will silently fail if the conversion cannot be accomplished. (besides, what would be that "somehow"?) If you want to store number types, why don't you make a Number base class and use polymorphism (virtual functions) to achieve what you want? – Tamás Szelei Apr 26 '11 at 14:29
  • @Tamás Szelei: by somehow i mean say wgen Datatype is an int type flag is set to one when it is double it is set to two so on so forth, virtual functions are what I am using right now but it is costing too much memory 2kb is all I have. – Hamza Yerlikaya Apr 26 '11 at 14:35
  • You seem to want discriminated union like [Boost.Variant](http://www.boost.org/doc/libs/1_46_1/doc/html/variant.html). – Ise Wisteria Apr 26 '11 at 18:24

1 Answers1

0

Maybe the Curiously recurring template pattern can help you. The idea is to inherit the base class with a template argument set to the derived class (this is legal because right after class Derived is written down, it is a valid identifier in the source). I don't know if this is more sparse with memory than virtual functions, but it certainly avoids them :).

If you have that low memory, maybe you should evaluate the option of moving to another language (C?) since C++ is not that lightweight on embedded systems.

Tamás Szelei
  • 23,169
  • 18
  • 105
  • 180