On Saturday, 28 May 2016 13:24:04 UTC+3, Heinz-Mario Frühbeis wrote:
> it took many time over the last times, because it is a great wish of
> mine to have this... different types in one collection (or such).
Alternative types put into one type is called 'union' in C and C++.
Search it up, it must be in C++ textbook you use for learning it.
The union objects can be elements of containers and arrays.
Can you tell ... why you have such a great wish? What you need it for?
>
> Now I have a solution..., first is an array, second is with a vector.
>
> The array is working well, output is:
> 1000
> 700
> 300
> NOT FOUND
> NOT FOUND
> FOUND at 2
> NOT FOUND
> NOT FOUND
>
> But the vector "makes" problems..., the output is:
> PUSHED_BACK 0x7fff63053760 1
> PUSHED_BACK 0x7fff63053770 1
> PUSHED_BACK 0x7fff63053780 2
> Das Programm ist abgestürzt. // The program has crashed
The 'Add_Vec <A> (2)->val' does likely crash at 'return vec[index];' that
has undefined behavior. If you want defined behavior (but not much more
pleasant) then perhaps use 'return
vec.at(index);' ... that will throw
instead of maybe crashing.
>
> The (first) question is: Why hasn't the vector 3 elements?
What "the vector" you mean? The static vector in 'Add_Vec<A>' will have
2 elements and the static vector in 'Add_Vec<B>' will have one element
if your code actually calls 'To_Vec' (call is commented out in posted
code but seems to be happening in posted output).
>
> Below you will find the source...
>
> A first other question is:
> Is there another, better way to realize it? (no void*, no boost...)
To realize what? There is 'union'. If you want examples of reinventing or
extending it well then there is 'boost::variant'. There are lot of other
mature "Variant" class implementations in various frameworks like COM,
Qt etc. Also there are (less convenient) "Any" class implementations.
Search engine vomits additionally lot of square wheels invented to that
theme.
What you particularly attempt to do does not work. You seemingly assume
that different instantiations of a template function somehow share
internal static variables. These do not.