C++模板实例用于其他模板时报错的问题咨询
问题分析与解决方案
咱们先来看看你写的代码:
#include <iostream> using namespace std; template <typename I> class A { I name; public: A(I n){ name = n; } void show() const { cout << name << "\t"; } }; template <template<typename I> class V> class B { V origen; public: B (V o){ origen = o; } }; auto main() -> int { cout << "[code.cpp]" << endl; A<int> a1(1); a1.show(); B<A> b1(a1); return 0; }
核心问题
你给类B用了模板模板参数template<typename I> class V,这意味着V代表的是一个模板(比如A这个模板本身),而不是一个具体的类实例(比如A<int>这种已经实例化后的类)。但你的构造函数却试图把A<int>的对象赋值给V origen——这就像你试图把一个苹果放进一个“水果模板”的框里,完全不是一个类型,编译器肯定会报错。
两种解决方案
方案一:保留模板模板参数,新增具体类型参数
如果确实需要用到模板模板参数(比如要在B里创建该模板的其他实例),可以给B再加一个模板参数,用来指定模板V的具体类型参数:
#include <iostream> using namespace std; template <typename I> class A { I name; public: A(I n) : name(n) {} // 建议用初始化列表,比赋值更高效 void show() const { cout << name << "\t"; } }; // 新增模板参数I,用来确定V的具体实例类型 template <template<typename I> class V, typename I> class B { V<I> origen; // 现在origen是具体的V<I>类型(比如A<int>) public: // 用const引用传参,避免不必要的拷贝,更合理 B(const V<I>& o) : origen(o) {} // 可以加个方法测试调用A的show void show_origen() const { origen.show(); } }; auto main() -> int { cout << "[code.cpp]" << endl; A<int> a1(1); a1.show(); cout << endl; // 这里要指定两个模板参数:模板A和具体类型int B<A, int> b1(a1); b1.show_origen(); cout << endl; return 0; }
方案二:直接使用具体类型作为模板参数(更常用)
如果只是想把A的实例包装进B里,不需要操作模板本身,直接让B接受具体的类型作为模板参数会更简单:
#include <iostream> using namespace std; template <typename I> class A { I name; public: A(I n) : name(n) {} void show() const { cout << name << "\t"; } }; // 直接接受具体类型T(比如A<int>) template <typename T> class B { T origen; public: B(const T& o) : origen(o) {} void show_origen() const { origen.show(); } }; auto main() -> int { cout << "[code.cpp]" << endl; A<int> a1(1); a1.show(); cout << endl; // 直接传入实例化后的具体类型A<int> B<A<int>> b1(a1); b1.show_origen(); cout << endl; return 0; }
这两种方案都能解决你的问题,具体选哪种取决于你实际的业务需求——如果需要在B里动态创建不同类型的V实例,选方案一;如果只是简单包装,方案二更简洁通用。
内容的提问来源于stack exchange,提问作者lfo212
相关产品推荐
相关产品推荐

