N
N
Nikita Gusakov2013-06-05 12:21:14
Programming
Nikita Gusakov, 2013-06-05 12:21:14

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;
    }
};

That's what I threw, but I can't enter in any way, how can I return not a union, but specifically data? Or is this impossible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
gaelpa, 2013-06-05
@hell0w0rd

You can overload type casting operators.

A
AxisPod, 2013-06-05
@AxisPod

Look in the direction of boost::any and boost::variant, I can give an implementation very close to boost::any, but without boost.

T
turboNOMAD, 2013-06-05
@turboNOMAD

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 question

Ask a Question

731 491 924 answers to any question