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]
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]
I mean, I want to get rid of that foreach(field : fields).
I found this variadic template loop implementation, but it is recursive. For performance resons this even worst than foreach loop
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]
So the question is.... Is it possible possible to achive result as on [listing 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. 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>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.