具有可变变量的嵌套C++模板

Nested C++ template with variadic

本文关键字:嵌套 C++ 模板 变量      更新时间:2023-10-16

我想知道是否可以嵌套C++模板并且仍然能够访问模板值? 解释一下,这是我目前拥有的:

template <int first, int... tail>
struct ConstIntVector:ConstIntVector<tail...>
{};
template <int first>
struct ConstIntVector<first>
{}; 
template<int f1, int... t1>
int prod(const ConstIntVector<f1, t1...>, const int* a) {
return f1 * (*a) + prod(ConstIntVector<t1...>(), a+1);
}

这样,我就可以在prod函数中访问f1值。但我想这样做:

template<ConstIntVector<int f1, int... t1>>
int prod(const int* a) {
return f1 * (*a) + prod<ConstIntVector<t1...>>(a+1);
}

有可能吗?

成员函数不允许使用部分模板专用化。但是您可以使用帮助程序结构:

namespace detail
{
template <typename T>
struct prodHelper;
template <int f1, int... t1>
struct prodHelper<ConstIntVector<f1, t1...> >
{
static int eval(const int* a) { 
return f1 * (*a) + prodHelper<ConstIntVector<t1...>>::eval(a+1);
}
};
}
template <typename T>
int prod(const int* a) {
return detail::prodHelper<T>::eval(a);
}

另一种选择是利用ConstIntVector结构来携带有用的信息:

template <int First, int... Tail>
struct ConstIntVector {
constexpr static int value = First;
using tail = ConstIntVector<Tail...>;
};
template <int First>
struct ConstIntVector<First> {
constexpr static int value = First;
using got_no_tail = void;
}; 
template <class CIV, typename CIV::tail* = nullptr>
int prod(const int* a) {
return CIV::value * (*a) + prod<typename CIV::tail>(a+1);
}
template <class CIV, typename CIV::got_no_tail* = nullptr>
int prod(const int* a) {
return CIV::value * (*a);
}

请注意,递归对于解决此类 TMP 问题既不是必需的,也不是可取的。首先,最好像这样简单地定义你的向量:

template <int... Is>
struct ConstIntVector{};

这样你也可以有零长度向量,这在处理边缘情况时很方便(见证std::array长度可以是 0 的事实(。

接下来,让我们编写我们的产品函数。我们将以两种方式修改它:首先,我们将通过按值简单传递ConstIntVector来推断整数,其次我们将使用包扩展来避免递归。

template<int... Is>
int prod(const int* a, ConstIntVector<Is...>) {
int index = 0;
int sum = 0;
int [] temp = {(sum += (a[index++] * Is))...};
return sum;
}

用法:

std::vector<int> v{1,2,3};
using v2 = ConstIntVector<4,5,6>;
std::cerr << prod(v.data(), v2{});

现场示例:http://coliru.stacked-crooked.com/a/968e2f9594c6b292

链接到高度优化的装配示例:https://godbolt.org/g/oR6rKe。

怎么样

template<int I>
int prod(const int* a) {
return I * (*a);
}
template<int I, int I2, int... Is>
int prod(const int* a) {
return I * (*a) + prod<I2, Is...>(a + 1);
}