我需要一组使用了可变数量值的初始化函数。我正在使用它们通过 Eigen 库实现收集操作。下面是我现在使用的方法,每个 vector 长度都有一个模板:
template<typename T1, typename T2>
inline void gather (Array<T1,4,1> &to, const Array<T2,Dynamic,1> &from, const Array<int,4,1> &index)
{
to << from[index[0]], from[index[1]], from[index[2]], from[index[3]];
}
template<typename T1, typename T2>
inline void gather (Array<T1,6,1> &to, const Array<T2,Dynamic,1> &from, const Array<int,6,1> &index)
{
to << from[index[0]], from[index[1]], from[index[2]], from[index[3]], from[index[4]], from[index[5]];
}
有没有办法用长度参数(上面代码段中的 4 和 6)参数化的单个模板替换像上面那样的更长的模板列表?如果是这样,是否可以使用 C++11 之前的语言规范来完成(我使用的是 Visual Studio 2010)?
我想保留逗号分隔值语法,因为我希望它在某些情况下可以产生编译时初始化(const from
和 index
)。不过,我的这个假设可能是错误的。初始化列表可以有 1 到 16 个值 - 无需担心列表为空。
最佳答案
不要在此设置中使用逗号初始化语法,这会很麻烦。此语法用于在使用文字时提高可读性,这不是您的情况。
相反,我会推荐这样的东西:
template<typename T1, typename T2, unsigned int SIZE, unsigned int INDEX>
struct gather {
gather(Array<T1,SIZE,1> &to,
const Array<T2,Dynamic,1> &from,
const Array<int,SIZE,1> &index)
{
to.col(INDEX) = from[index[INDEX]];
gather<T1,T2,SIZE,INDEX+1>(to,from, index);
}
};
template<typename T1, typename T2, unsigned int SIZE>
struct gather<T1,T2,SIZE,SIZE>{
gather(Array<T1,SIZE,1> &to,
const Array<T2,Dynamic,1> &from,
const Array<int,SIZE,1> &index)
{
}
};
这很好地产生了相同的效果,但是是静态的(没有循环)。
由于函数的部分模板特化限制,我在这里使用结构,但由于内联,它应该归结为相同的。
关于c++ - 可变长度初始值设定项的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376306/