STL container with typical / template variables

I just wanted to do one of the following:

template <typename T>
class gvar {
private:
    T var;
public:
    gvar(T var) : var(var) {}
};

std::stack<gvar> some_stack;

g ++ spits out all kinds of errors about how gvar is not a type. Is this possible relatively easy? I prefer not to use boost :: any / boost :: variant.

edit:

To clarify what I want:

Std :: stack, which can contain variables of different types (just primitives in order).

+3
source share
7 answers

In general, if you want polymorphism, you would use a base class:

class GVarBase
{
public:
  virtual ~GVarBase() {}
};

template <typename T>
class GVar: public GVarBase
{
public:
private:
  T mVar;
};

std::stack< std::unique_ptr<GVarBase> > stack;

Note that with the current code that you have, std::stack< GVar<int> >it won’t even work, a default constructor is required.

+2
source

gvar , . :

std::stack< gvar<int> > some_stack;
+7

, . , std::stack<gvar<int> >, , Boost:: Any.

+5

gvar, :

std::stack<gvar<int> > some_stack;
+3

, , . , .

boost::tuple<gvar<double>,gvar<int>,gvar<double> > myItems;

, , :

boost::tuple<double,int,double> myItems;
+1

No. There is no way to do what you are trying to do. More clarity about the problem you are trying to solve with this attempt may allow me to create a workaround.

+1
source

It seems you need something like this:

class gvar {
        struct base_val { 
                virtual ~base_val() {} 
        };
        template <class T>
        struct con_value : base_val{
                con_value(T val): value(val) {}
                T value; 
        };      
        base_val *var;
public:
        template <typename T>
        gvar(T var) : var(new con_value<T>(var)) {}
        template <typename T>
        T* getValue() { 
                con_value<T> *ptr = dynamic_cast<con_value<T>*>(var);
                if(ptr == NULL) return NULL;
                return &ptr->value;
        }
};

std::stack<gvar> some_stack;

(link to ideon with a working example http://www.ideone.com/gVoLh )

This is simplified boost::any, so if you can, just use it boost::anyinstead.

0
source

Source: https://habr.com/ru/post/1788643/


All Articles