【问题标题】:c++ variadic template argument iteratingc++ 可变参数模板参数迭代
【发布时间】:2016-07-08 02:50:04
【问题描述】:

我在这些事情上相当缺乏经验,但我正在尝试创建一个模板函数,该函数在“旋转”参数(参见下面的示例)处评估一个 n 变量函数并返回一个向量所有这些值。

例如,对于具有函数 f(x,y,z) 的 n=3,返回的三元组\向量应该是

f(x,0,0), f(0,x,​​0), f(0,0,x ) >

我需要的原始版本可能如下所示(不一定正确\工作)

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 在编译时是众所周知的。

【问题讨论】:

  • 您的 f() 函数不采用明确的值列表作为参数,而是让您的 f() 函数采用值向量。用值填充向量,作为参数传递,变得微不足道。无需处理可变参数函数。
  • 1) 我想我可以毫无问题地使“f”向量赋值……尽管当“n”=1 时它可能是多余的。 .... 2)“变得微不足道”没有帮助...特别是,我不确定它如何帮助在编译时完成。

标签: c++ templates c++11 generic-programming


【解决方案1】:
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.

【讨论】:

  • 谢谢,这看起来很不错,正是我需要的! (非常希望我自己知道自己需要什么,哈哈)
  • 我猜(void(Is), 0)... 在一个完全通用的情况下应该是(void(Is), Function::InComponent(0) )...
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 2016-09-20
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
相关资源
最近更新 更多