有两种可能的方式来做到这一点,而不使用继承,但这也可能取决于一些决定因素。第一个问题是:在创建外部类的实例时,已知的是模板容器的类型。如果是的话,这是一个容易写作的课程。如果不是,那么仍然可以完成,但会涉及更多的工作。如果案例不知道,有两种方法可以做到这一点,第一种方法是通过不制作这个类模板来避免这种情况。第二个涉及更多的工作,其中一些关于如何定义这个类的逻辑将被显示。
伪代码: - 1种情况,其中类型是已知的在创建现在
#include <map>
template<class T>
class MyContainer {
// ... Class Variables, Constructors & Methods
}
// For Demonstration We will say that `T` is known to be an int upon instantiation
class MyClass {
private:
std::map< std::string, MyContainer<int> > maps_;
public:
MyClass() {}
~MyClass() {
// Clear Out Map
}
void addItem(std::string& str, int value) {
maps_.insert(std::make_pair(str, MyContainer<int>(value));
}
};
对于其中类型没有使用方法,无需模板化包装称为第二个情况下,你需要知道的这个类可以支持的所有类型,您将需要创建其中每个类的typedef
。
伪码 - 2情况如果不知道类型:
#include <map>
template<class T>
class MyContainer {
// ... Class Variables, Constructors & Methods
}
// For Demonstration We will say that `T` is unknown before instantiation
class MyClass {
public:
typedef MyContainer<int> INTS;
typedef MyContainer<float> FLOATS;
typedef MyContainer<double> DOUBLES;
// And Do This For Every Type This Class Will Support.
private:
std::map< std::string, INTS > mapInts_;
std::map< std::string, FLOATS > mapFloats_;
std::map< std::string, DOUBLES > mapDoubles_;
// And You Will Need A Container For Each Supporting Type
public:
MyClass() {}
// If You Have Constructors Other Than Default That Excepts Parameter Types
// You Will Need A Constructor For Each Supporting Type
~MyClass() {
// Clear Out All Maps
}
void addInts(std::string& str, MyClass::INTS);
void addFloats(std::string& str, MyClass::FLOATS);
void addDoubles(std::string& str, MyClass::DOUBLES);
// And You Will Need A Corresponding Function For Each Type This Class Supports.
};
有作为“模板类”没有这样的事。 C++有类模板。类模板不是类。你的描述很不明确。请显示更多你的代码。 –