[英]C++ variadic function: use number of parameters as template argument
我有一个可变坐标数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).
来创建新矢量vec4 a=vec4(1,2,3,4); vec4 b=a.xyxz; //b is (1,2,1,3).
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]
像这样:
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);
}
它也可以使用旧式的函数签名语法(在这种情况下,我只是更喜欢尾随返回类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.