简体   繁体   中英

Storing a variadic template class into std::vector

template<typename...Args> 
class something {
     //...
};

class storage {

  template<typename...Args>
  void build_something_class_obj() {
     //...
  }
private:
  std::vector<???> m_container;
};

How can I store classes like that? Args may vary so I can't make storage template class

something is a template not a type, but you can only have objects of one type in a vector . Different instantiations of something are completely unrelated, unless you use a base class:

struct something_base {};

template<typename...Args> 
class something : something_base {
     //...
};

And now you can have a std::vector<std::unique_ptr<something_base>> and push instances of different isntantiations of something into that vector.

There are alternatives for type erasure (eg std::any , std::variant ). What is most appropriate depends on what you want to do with the elements in the vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM