【问题标题】:Template parameter to change in a for loop?在for循环中更改模板参数?
【发布时间】:2014-12-08 12:22:20
【问题描述】:

我有一个与(我认为)C++(C++11 之前的版本,我目前无法升级)模板编程(和“特征”)相关的问题。

我的目标:

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

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

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

例如,我有类 Derived1 和 Derived2(在 Derived.hpp 文件中定义)覆盖其 Root 父类的函数 open。 我有一个模板函数 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 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;
       };

【问题讨论】:

标签: c++ templates c++11


【解决方案1】:

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

“循环” 在模板定义上,你可以有类似的结构,例如

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

template<>
struct A<0> {
     typedef void X;
};

【讨论】:

  • @MyName 并不是所有的希望都消失了。查看我的更新。
  • 嘿,这很聪明!我需要更好地理解你的观点......但是,请深入挖掘。绝对!
  • @MyName THX ;-)。不是一个那么聪明的样本,但你似乎已经掌握了。这种技术通常称为Template Metaprogramming。最突出的示例之一是如何使用这种技术创建阶乘值。
【解决方案2】:

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

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>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2012-07-25
    • 2012-01-07
    相关资源
    最近更新 更多