要在 for 循环中更改的模板参数

Template parameter to change in a for loop?

本文关键字:参数 for 循环 要在      更新时间:2023-10-16

我有一个与(我认为(C++(在 C++11 之前,我暂时无法升级(模板编程(和"特征"(相关的问题。

我的目标:

我有不同的(但非常相似(的类(已经从具有新功能和成员的基类派生的类(。

我编写了一个 Template 类,该类继承自这些类中的任何一个,并使用多态函数"open"从数据库中收取与特定类相关的所有成员和信息。

我想

到这个策略是因为在我想使用这个实例化类(及其所有成员(作为其他函数的输入之后。我本可以使用开关/案例架构来完成它(我认为..但是在这里我的模板类可以从模板参数中的类继承......(,但我想在这里避免它,因为它已经在之后被大量使用。

例如,我有类 Derived1 和 Derived2(在 Derived.hpp 文件中定义(,它们覆盖了它们的根父类的函数打开。我有一个模板函数MyClass曾经使用过 MyClass currentClass((,或 MyClass currentClass(( 可以做我想要的(下面的代码(。

问题:

是否可以编写一些让我有可能制作 for 循环的东西?

类似的东西

For (auto i=1; i<N; ++i)
{ 
MyClass<DerivedType[i]> currentClass();
--- other things to do with my currentClass ---
}

对我来说,现在我的 DerivedType(s( 是"类型"(请参阅下面 traits.hpp 代码段中的结构(,我什至不知道我是否可以将它们放在容器中(如向量(......也许在 C++11 中,我可以为所有派生类型定义一个枚举类(这是真的吗?(,但这里有 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:

(包括"特质.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 文件

(包括"派生.hpp"(

    struct DerivedType1 {
                    typedef Derived1 type;
       };
       struct DerivedType2 {
            typedef  Derived2 type;
       };

模板在编译时实例化,for()循环在运行时计算。
所以不,你不能这样做。

"循环">模板定义,您可以使用诸如

template<int N>
struct A {
     typedef A<N - 1> X;
};
template<>
struct A<0> {
     typedef void X;
};

使用可变参数模板,您可以执行以下操作:

template <typename T>
void do_job()
{
    // job for one type
    // MyClass<T> currentClass;
    // ...
}

template <typename ... Ts>
void do_jobs()
{
    // trick to unroll the types sequentially
    std::initializer_list<int>{(do_job<Ts>(), 0)...};
}

并称之为:

do_jobs<Derived1, Derived2>();