template template parameter
测试代码
C++ 11里面
#include <stdexcept> #include <iostream> #include <memory> #include <vector> #include <string> #include <deque> template<typename T> using Vec = std::vector<T, std::allocator<T>>; class A { private: int a = 0; int b = 2; public: A() = default; A(int pa1, int pa2) :a(pa1), b(pa2) { printf("A Construct call!"); }; }; template<typename T,template<class> class Container> class XCls { private: Container<T> elem; public: XCls() { for (int i = 0; i < 4096; i++) elem.insert(elem.end(), T(i,4096-i)); } }; int main() { XCls<A, Vec> test1; }
在C++ 14里面这样已经不会报错了
#include <stdexcept> #include <iostream> #include <memory> #include <vector> #include <string> #include <deque> class A { private: int a = 0; int b = 2; public: A() = default; A(int pa1, int pa2) :a(pa1), b(pa2) { printf("A Construct call!"); }; }; template<typename T,template<class> class Container> class XCls { private: Container<T> elem; public: XCls() { for (int i = 0; i < 4096; i++) elem.insert(elem.end(), T(i,4096-i)); } }; int main() { XCls<A, std::vector> test1; }
示例结果