C++ value from union structure using generic class



Hi
I am out of ideas in trying to solve the below issue. I have a union
structure which is stored in a map and indexed by a key. I need to
write a class to cache in the value stored in the structure. It could
be easily done by having a templatised class. But the guru's have
proclaimed that proliferation of classes is an issue.
Now to solve this, I can have a generic class having a templatised
function say get_value to return the value stored in the union.
I can make the key value identifying the union in the map as
templatised.
Pass this templatised index to the generic class which has a
templatised constructor.
The problem is how would I pass the type from the constructor to the
get_value function.
i woud require the type information in the get_value function to
atleast throw an compile time error.
Just bear with me if you have come this far.. a sample code is shown
below
// the union structure holding the value
union u_data {
int d_int_data;
float d_float_data;
void* d_user_def_data;
};

// templatised index class to identify the union structure which is
stored in a map
<template data_type>
class Index{
int key; // id associated with the union structure
}

class Conf_attrib
{
public:

union u_data d_data;
template<typename T>
Conf_attrib(Index<T> b){
// do processing here to Index into the map and get the union and
// assign it to the class data d_data
}

template <typename R>
void get_data(R& a)
{ // for user def type
a =
*(reinterpret_cast<R*>(d_data.d_user_def_data));
};

// specialisation for int and float
template <>
void get_data(int& a)
{
a = d_data.d_int_data;
};

template <>
void get_data(float& a)
{
a = d_data.d_float_data;
};

private:
Conf_attrib(const Conf_attrib&);

};
This woud work fine as it is. But i would want to ensure that if the
user is passing an index to get a union whcih is holding a float value
and in the get_value he passes accidentally an int , it should give a
compile time error.
To return the user a compile time error i would have to know the type
he passed in the construction of the class, so that i could do some
trick by checking using trait classes to throw a compile time error.
any ideas on the same?

.



Relevant Pages