【问题标题】:C++ variadic function: use number of parameters as template argumentC ++可变参数函数:使用参数数量作为模板参数
【发布时间】:2014-10-24 20:31:40
【问题描述】:

我有一个可变坐标计数L 的向量类template <unsigned int L> class Vec

我想实现 glsl 的字段选择功能,它允许您通过选择 vec4 a=vec4(1,2,3,4); vec4 b=a.xyxz; //b is (1,2,1,3). 来创建新向量

在我的程序中,我想创建类似的东西:

Vec<3> a={7,8,9};
Vec<4> b=a.select(0,2,2,1); //each argument is an index of the coordinate to use. 
Vec<5> c=b.select(0,1,2,3,1);

解决方案:

template<typename... Args,unsigned int S=sizeof...(Args)> Vec<S> select(Args&&... args){
    Vec<S> result;
    int indices[S]={args...};
    for(int i=0;i<S;i++){
        result[i]=this->v[indices[i]]; //v is the float array that stores the values.
    }
    return result;
}

还有一些荒谬的例子,看看它是否有效:

Vec<3> a={7,8,9};
Vec<9> b=a.select(0,0,1,1,0,0,1,1,2);
Vec<1> c=a.select(2);

a=[7,8,9]
b=[7,7,8,8,7,7,8,8,9]
c=[9]

【问题讨论】:

  • this question的可能重复
  • template &lt;const unsigned int L&gt; class Vec remove const,这是多余的

标签: c++ templates c++11 variadic-functions variadic


【解决方案1】:

像这样:

template<int N>
class Vec {};

template<typename... Args>
auto foo(Args&&...) -> Vec<sizeof...(Args)>;

int main()
{
    auto v = foo(1,2,3);
    Vec<1> vv = foo(5);
}

它也适用于旧式函数签名语法(在这种特殊情况下,我只是更喜欢尾随返回类型)。

【讨论】:

  • 谢谢您,您的方法非常好。我是这样实现的。代码见上。
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 2017-08-04
  • 2012-08-14
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多