Home > database >  How to make a vector of a type and its name
How to make a vector of a type and its name

Time:07-06

I have several classes, and I want to make their objects. Each object has different name so as to differentiate with any other object (may be of same type). I want to give the responsibility of making objects to a different function, which takes a vector of {name, class type} elements. Lets say I have 2 structs:

struct A
{
   int i;
}


struct B
{
   int i;
   double d;
}

struct Type
{
    std::string name;    

    template<typename T>
    T t;

    template<typename T>
    using type = decltype(t);
};

std::vector<Type> v{{"ObjA1", A()}, {"ObjB", B()}, {"ObjA2", A()}};

void fun(std::vector<Type> vec)
{
   // use vec to create objects
}

Is this possible to achieve ? Structures A and B are actually classes, provided by some external framework.

CodePudding user response:

I have several classes, and I want to make their objects....

Is this possible to achieve ?

Yes, in you can. Since you know the types, I would suggest a std::variant<A, B, ...> as a template parameter to the std::vector<Type<...>>.

This required however your struct Type be a class template.

template<typename T> struct Type
{
    std::string name;
    T t;    
    using type = decltype(t);
};

Then we can provide a helper alias type:

#include <variant>

// helper type alias for variats
template<typename... Ts>
using VariantsType = Type<std::variant<Ts...>>;

Now you can write

std::vector<VariantsType<A, B, C>> v{
    {"ObjA1", A{}}, {"ObjB", B{}}, {"ObjA2", A{}}
};
v.emplace_back(VariantsType<A, B, C>{"ObjA3", A{}});
v.emplace_back(VariantsType<A, B, C>{"ObjC1", C{}});
// ... so on

See a demo

CodePudding user response:

If you know what type will be used, you can use variant. If you can not list the types you will use, you can use any. Like

  std::vector<std::any> example;
  example.push_back(1);
  example.push_back("1");
  example.push_back(std::make_pair(1, "1"));
  • Related