c++ - How to create a template class with a template container of different objects as a parameter -
how can declare template class (a library of components) take vector containing components parameter? here stripped down version of code example:
// in library.h using namespace std; template<typename t, template <typename, typename = std:allocator<t>> class container> class library { container<t> comp_lib; library(container<t> &vc) {comp_lib = vc} }; // in mainprogram.cpp #include "library.h" // other includes... using namespace std; int main() { library<int, vector> intlib; return(0); }
as mentioned before meant library of components. instead of holding vectors containing integers library template meant hold vectors containing general components, vectors containing resistors, vectors containing capacitors , vectors containing inductors. resistors, capacitors , inductors derived classes component base class.
when run code, not compile , receive these error messages:
c2079: 'intlib' uses undefined class 'library' on line [ library intlib ] in mainprogram.cpp
c3855 'library': template parameter 'c' incompatible declaration on line [ }; ] in library.h (the last line)
c3855 'library': template parameter 'vector' incompatible declaration on line [ }; ] in library.h (also, last line)
i've looked @ lots of different articles concerning template template parameters, answer has been useful far although doesn't seem solve problem i'm having: template class template container
the desired result able write statements such as:
library<resistor, vector<resistor>> resistor_lib; library<capacitor, vector<capacitor>> capacitor_lib; library<inductor, vector<inductor>> inductor_lib; library<component, vector<component>> component_lib;
in main using same template.
thanks, appreciated
you need template the container , let tell stored type. standard containers means of value_type
definition. like:
template <typename tcontainer> class library { private: tcontainer container_; public: using container_type = tcontainer; using value_type = typename tcontainer::value_type; library(const container_type &initvalues) { std::copy(initvalues.begin(), initvalues.end(), std::back_inserter(container_)); } [...] };
this should work vector
, list
, can "back_inserted". additionally can reference container , object types means of container_type
, value_type
.
instances declared like
library<std::vector<int> > lib(someinitializer);
Comments
Post a Comment