【发布时间】:2014-12-08 12:22:20
【问题描述】:
我有一个与(我认为)C++(C++11 之前的版本,我目前无法升级)模板编程(和“特征”)相关的问题。
我的目标:
我有不同(但非常相似)的类(已经从具有新功能和成员的基类派生的类)。
我编写了一个模板类,它继承自这些类中的任何一个,并使用多态函数“open”从数据库中收取与特定类相关的所有成员和信息。
我想到了这个策略,因为我想使用这个实例化的类(及其所有成员)作为其他函数的输入。 我本可以使用 switch/case 架构来完成它(我认为.. 但在这里我的模板类可以从模板参数中的类继承......),但我想在这里避免它,因为它之后已经被大量使用。
例如,我有类 Derived1 和 Derived2(在 Derived.hpp 文件中定义)覆盖其 Root 父类的函数 open。
我有一个模板函数 MyClass 曾经使用过
MyClass
问题:
是否有可能写一些东西让我有可能制作一个 for 循环?
类似
For (auto i=1; i<N; ++i)
{
MyClass<DerivedType[i]> currentClass();
--- other things to do with my currentClass ---
}
现在对我来说,我的 DerivedType(s) 是“类型”(参见下面的 traits.hpp sn-p 中的结构),我什至不知道我是否可以将它们放入容器中(如向量) … 也许在 C++11 中我可以为所有 DerivedTypes 定义一个枚举类(是真的吗?),但这里是 C++03?
我承认完全迷路了……
非常感谢您提前提出任何建议。
(工作)主要
(包括“MyClass.hpp”)
int main(int, char* [])
{
GlobalClass GlobalItem(); //global class encapsulating all the info of each item from the database
//connection to the database
//DerivedType1 case
MyClass<DerivedType1> CurrentClass();
GlobalItem.AddCurrentClass();
//with a for loop or the like I can use the fact that at each loop the class is declared only inside the { … } and then each time the destructor
//is automatically called
CurrentClass.clear();
CurrentClass = MyClass<DerivedType2>();
GlobalItem.AddCurrentClass();
return 0;
}
这里是模板类 MyClass.hpp:
(包括“traits.hpp”)
template <class Traits>
class MyClass : public Traits::type
{
private:
typedef typename Traits::type BaseType;
protected:
std::string currentType_;
public:
//constructor
MyClass() : BaseType() { this->open() }
//destructor
virtual ~MyClass();
};
这里是由作用域 :: 运算符运行的 traits.hpp 文件
(包括“Derived.hpp”)
struct DerivedType1 {
typedef Derived1 type;
};
struct DerivedType2 {
typedef Derived2 type;
};
【问题讨论】: