There are 2 classes A and B. You need to create a container separately for each class through the create method which the template fills the container with a type depending on the parameter of which it was passed.

template <typename T> vector<T> create(tring tipe) { vector<T>test; if (tipe == "a") { test.push_back(A()); } if (tipe == "b") { test.push_back(B()); } return test; } void d() { vector<A>a; vector<B>b; a = create<A>("a"); b = create<B>("b"); } 

when building this error, 'void std :: vector <A, std :: allocator <_Ty :: push_back (_Ty &&)': cannot convert argument 1 from 'A' to 'const B &'

how to solve it?

  • a = create <A> ("a")? - goldstar_labs
  • yes, I forgot to screw up here - whoami
  • "... which fills the container with a type depending on the parameter of which it was passed" - this is impossible to implement. The function parameter is the runtime value. The type of the container element is strictly defined at the compilation stage. It is impossible to directly place in the container one whose type is not fixed at the compilation stage. - AnT

2 answers 2

The problem here is that the type of the element that can be put in the vector is specified by the template parameter T at the compilation stage, and not by the line at the execution stage. Accordingly, to create a vector with one element is much simpler:

 template <typename T> vector<T> create(void) { vector<T> test{}; test.push_back(T{}); return test; } 

    Maybe so?

     #include <vector> struct A {}; struct B {}; template<typename T> std::vector<T> Create(const T& o) { std::vector<T> ret{o}; return ret; } int main() { std::vector<A> vA = Create(A{} ); std::vector<B> vB = Create(B{} ); return 0; } 
    • And why dummy argument? - bipll
    • for instantiating a template - Stanislav Petrov
    • Well, if A and B take a different number of parameters, say A (5); B ("test", 0); - whoami
    • Why then just do not write Create<A>() ? The same number of characters in the call places, but more in the function header --- not to mention the fact that the compiler is now formally obliged to create an object every time. - bipll pm