On 07/31/2015 05:01 AM, dariomt@gmail.com wrote:
Hi all,
Say I have a compile-time map of pairs, and I need to
access the correct element given a value at runtime and do something
with that type. That something would be the same for any of the mapped
types (e.g. calling an overloaded function that would then do the right
thing depending on the type).
The value would typically be an enum.
Is there anything in the Boost libraries to help with this?
If I used C++11, would there be a simple solution to this?
Regards
PS: I cannot use Boost.Variant
I've tried an alternative variant declared as:
template
< typename... Keys
, typename... Vals
struct map
< key_val_var...
: key_val_var...
{
private:
typename std::aligned_union::type
my_storage;
std::size_t
my_which;
...
}'
where key_val_var is:
template
struct key_val_var
{
public:
using key=Key;
protected:
template
static
void
construct
( void*storage
, Args&&... args
)
{
new (storage) Val(std::forward<Args>(args)...);
}
static
void
destruct
( void*storage
)
{
auto p=static_cast(storage);
p->~Val();
}
static
Val*
get_val_ptr
( void*storage
)
{
auto p=static_cast(storage);
return p;
}
When assigning a new value to this variant, the old
value has to be destroyed based on the *runtime* value
of my_which. This is done by indexing into a
temp vector of the static destructs in the superclasses:
void
destroy_which()
{
typedef void(*destructor_t)(void*);
destructor_t destructors[]=
{key_val_var::destruct...} ;
destructors[my_which](storage());
}
I'm guessing you could do something similar for
the get_val_ptr's in the superclass.
If you think it would help, I could post the code.
-regards,
Larry