简体   繁体   English

可变模板循环,非递归

[英]Variadic template loop, non recursive

I have some function, which performs complex drawings.我有一些功能,可以执行复杂的绘图。 [in pseudocode] [伪代码]

template<typename fields...>       // field names of Brush class
void someFunction(){    
  for(very large loop){

     Brush brush = getBrush();
     int x;

     foreach(field : fields){     // <--- this somehow should be replaced
        x = brush.*field;
        brush.update(x);
     }

  }    
}

[listing 1] [清单 1]

I call it:我称之为:

someFunction<&Brush::xPos1, &Brush::xPos2, &Brush::xPos3, &Brush::xPos4>()

And I want compiler to generate something like this:我希望编译器生成这样的东西:

void someFunction(){    
  for(very large loop){

     Brush brush = getBrush();
     int x;

        x = brush.xPos1;
        brush.update(x);

        x = brush.xPos2;
        brush.update(x);

        x = brush.xPos3;
        brush.update(x);

        x = brush.xPos4;
        brush.update(x);

  }    
}

[listing 2] [清单 2]

I mean, I want to get rid of that foreach(field : fields).我的意思是,我想摆脱那个 foreach(field : fields)。


I found this variadic template loop implementation, but it is recursive.我找到了这个可变参数模板循环实现,但它是递归的。 For performance resons this even worst than foreach loop对于性能响应,这甚至比 foreach 循环更糟糕

int a;

template <class T>
void print(const T msg)
{
    a = msg;
}


// And this is the recursive case:
template <class A, class... B>
void print(A head, B... tail)
{
    a = head;
  print(head);
  print(tail...);
}

[listing 3] [清单 3]


So the question is.... Is it possible possible to achive result as on [listing 2]?所以问题是......是否有可能达到 [清单 2] 上的结果? If yes, than how?如果是,比如何?

I see no real point in doing this.我认为这样做没有任何意义。 The compiler should optimize both the for loop and recursive template to the same code.编译器应该将 for 循环和递归模板优化为相同的代码。 In any case, something like this should work:无论如何,这样的事情应该有效:

struct Brush {
    int xPos1, xPos2, xPos3, xPos4;
    void update(int) {}
};

typedef int Brush::* Field;

template<Field...fs>
void Foo()
{
    Brush brush;
    int a[] = { (brush.update( brush.*fs ),0)... };
}

int main()
{
    Foo<&Brush::xPos1, &Brush::xPos2, &Brush::xPos3, &Brush::xPos4>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM