gpt4 book ai didi

c++ - 带有可变参数的嵌套 C++ 模板

转载 作者:太空狗 更新时间:2023-10-29 20:21:15 24 4
gpt4 key购买 nike

我想知道是否有可能拥有嵌套的 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);
}

关于c++ - 带有可变参数的嵌套 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45012439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com