2016-07-08 123 views
5

我在這種事情上很缺乏經驗,但我試圖創建一個模板函數來評估在「rotate」參數下的可變函數(參見下面的示例),並返回一個向量所有這些價值。C++ variadic模板參數迭代

例如爲Ñ = 3與函數˚F(X,Y,Z)所返回的三重\載體應該是

< ˚F(X,0,0), ˚F(0,X,0),˚F(0,0,X)>

天真的版本我需要什麼可能看起來像以下(不neces sary correct \ working)

typedef FunctionSignature Function; 

template<class Function, size_t Dimensions> 
std::array<Function::Out,Dimensions> F(Function::InComponent x) 
{ 
    std::array<Function::Out,Dimensions> Result; 

    for (i=0; i<Dimensions; i++)  
    Result[i] = Function::f("rotate((x,0,...,0),i)"); 

    return Result; 
} 

但是如何製作rotate的東西。

我也希望運行時for可以以某種方式被消除,因爲n在編譯時是衆所周知的。

+0

取而代之,您的'f()'函數將明確的值列表作爲參數,而您的'f()'函數取值爲一個向量。用值填充矢量,作爲參數傳遞,變得微不足道。無需處理可變參數函數。 –

+0

1)我沒有問題,使'f'向量值我猜...雖然它可能是冗餘'n'= 1時。 .... 2)「變得微不足道」並沒有幫助... 特別是,我不確定它是如何幫助它在編譯時完成的。 –

回答

5
template<class Function, size_t... Is, size_t... Js> 
typename Function::Out call_f(typename Function::InComponent x, 
           std::index_sequence<Is...>, 
           std::index_sequence<Js...>) { 
    return Function::f((void(Is), 0)..., x, (void(Js), 0)...); 
} 

template<class Function, size_t Dimensions, size_t... Is> 
std::array<typename Function::Out, Dimensions> F(typename Function::InComponent x, 
               std::index_sequence<Is...>) 
{ 
    return {{ call_f<Function>(x, std::make_index_sequence<Is>(), 
           std::make_index_sequence<Dimensions - Is - 1>())... }}; 
} 

template<class Function, size_t Dimensions> 
std::array<typename Function::Out,Dimensions> F(typename Function::InComponent x) 
{ 
    return F<Function, Dimensions>(x, std::make_index_sequence<Dimensions>()); 
} 

對於C++ 11,在SO上搜索執行make_index_sequence

Demo

+0

謝謝,這看起來非常好,正是我所需要的! (有一個很大的希望,我知道我自己需要什麼,lol) –

+0

我想'(void(Is),0)...'應該是'(void(Is),Function :: InComponent(0))。 ..'在一個完全通用的情況下 –