Answer the question
In order to leave comments, you need to log in
Implementing dynamic typing in c++?
Please tell me how to implement this?
class Variable
{
private:
int type;
union Value {
char sign;
int num;
} value;
public:
static const int SIGN = 1;
static const int NUM = 2;
Variable(char val)
{
type = SIGN;
value.sign = val;
}
Variable(int val)
{
type = NUM;
value.num = val;
}
Value get()
{
return value;
}
};
Answer the question
In order to leave comments, you need to log in
Look in the direction of boost::any and boost::variant, I can give an implementation very close to boost::any, but without boost.
You can on templates. But you do understand that union members are in the same place in memory and you cannot work with more than one at the same time, right?
template<typename T> Variable::get()
{
return (T)value;
}
template<> Variable::get<int>()
{
return value.num;
}
template<> Variable::get<char>()
{
return value.sign;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question