2016-07-08 122 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))。 ..'在一个完全通用的情况下 –