2013-10-04 4 views
-2

복잡한 그림을 수행하는 몇 가지 기능이 있습니다.Variadic 템플릿 루프, 비 재귀

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

그리고 컴파일러는이 같은 생성 할 : [의사에]

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

    }  
} 

[1 목록] 내가 전화

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

    }  
} 

[2

목록을 ]

I mea n, 나는 foreach (field : fields)를 없애고 싶다.


이 가변적 템플릿 루프 구현을 찾았지만 재귀 적입니다. 성능 resons 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...); 
} 


그래서 질문이 ....이 [2 목록]에 같은 결과를 실현하려 가능 가능 [3 목록]? 그렇다면, 어떻게?

+1

'fields' 가변 팩, 당신은 이동 포인터 – Manu343726

+0

를 전달하는 유형의 집합이며, (그들이 dessigned하지 않는 방식으로 기능을 사용하는 다형성 (polymorphism)에 대해 대신 배우 : 어떤 경우,이 같은 작업을해야합니다 그리고 전혀 의미가 없습니다.) – Manu343726

+1

필자는 컴파일러가 4-iterations 루프를 풀 것이라고 기대합니다. – jrok

답변

3

이 작업을 수행 할 때 실제적인 의미는 없습니다. 컴파일러는 for 루프와 재귀 템플릿을 동일한 코드로 최적화해야합니다.

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>(); 
} 
+0

알다시피, 나는 단지 내 모든 프로파일이 -O0 모드에 있다는 것을 알았다. 맞습니다 - 템플릿 재귀 루프를 최적화합니다. [link] (http://goo.gl/gGpeOa) 지적 해 주셔서 감사합니다. – tower120

+0

오, 아니, clang이 그것을 최적화하지 않으려 고합니다. http://goo.gl/7T6g5c – tower120

+0

int a [] = {fs ...}에 대해 알고 있습니다. 하지만이 구문은 처음으로 볼 수 있습니다. 어디에서이 구문을 읽을 수 있습니까? int a [] = {(brush.update (brush. * fs), 0) ...}; 고맙습니다. – tower120