C++ 可变参数函数 : use number of parameters as template argument

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

我有一个 vector 类template <unsigned int L> class Vec变量坐标计数L .

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

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

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);
}

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

关于C++ 可变参数函数 : use number of parameters as template argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25591822/

相关文章:

c++ - 在 Windows 中调试 QT 5.8 和打开 QFileDialog 时,gdborig.exe 随机崩溃

c++ - 文件夹结构 - 良好做法

c++ - 使用 getline 时遇到的问题

c++ - 函数模板和类模板有什么区别?

c++ - 从模板包生成所有大小为 N 的子包

c++ - 如何从 8 位整数中获得大于 8 位的值?

c++ - 通过循环传递不同的数据类型

c++ - 从元组中解包参数

c++ - 声明后初始化 C++ 模板类

c++ - 可变参数模板构造中的隐式 std::pair 构造