boost 元组如何“获得”?方法工作?

发布于 2024-12-29 05:57:53 字数 184 浏览 2 评论 0原文

在深入研究优秀的 boost 元组类 (tuple_basic.hpp) 的源代码后,我可以看到在“get”方法中使用了递归模板化算法来访问元组成员。

我很难理解的是如何将数字模板参数映射到特定的成员名称?另外,递归模板函数不会总是收敛到第一个元素(如递归模板函数的停止条件) , get<0>())?,如何访问大于零的元素?

After delving into the source of the excellent boost tuple class (tuple_basic.hpp), I can see that a recursive templated algorithm is used in the 'get' method for accessing the tuple members.

What I'm struggling to understand is how a numeric templated parameter can be mapped into a specific member name?, additionally, won't the recursive template function always converge to the first element (as in, the stop condition of the recursive template function, get<0>())?, how are elements greater than zero accessed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤寂小茶 2025-01-05 05:57:53

作为一个小例子,您可以想象这样的东西 - 现在只是一个固定类型的元组:

template <int N> struct MyTuple : MyTuple<N - 1>
{
    T data;
};
template <> struct MyTuple<0> { };

现实世界的解决方案当然会有数据类型的可变模板参数,并且还会提供一个可变构造函数,构造 data 包含第一个元素,并将其余元素传递给基本构造函数。

现在我们可以尝试访问第 i 个元素:

template <int K> struct get_impl
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return get_impl<K - 1>::get(static_cast<MyTuple<N - 1>&>(t));
    }
};
template <> struct get_impl<0>
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return t.data;
    }
};

这里的关键是当 K = 0 时进行专门化,提取实际元素,并建立继承层次结构直到你到达那里。最后,我们通过函数模板弹射元组类型推导:

template <int K, int N> T & get(MyTuple<N> & t)
{
    return get_impl<K>::get(t);
}

As a baby example, you can imagine something like this - just a tuple of one fixed type for now:

template <int N> struct MyTuple : MyTuple<N - 1>
{
    T data;
};
template <> struct MyTuple<0> { };

The real-world solution would of course have variadic template parameters for the data types, and would also provide a variadic constructor, constructing data with the first element and passing the remaining elements to the base constructor.

Now we can try and access the ith element:

template <int K> struct get_impl
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return get_impl<K - 1>::get(static_cast<MyTuple<N - 1>&>(t));
    }
};
template <> struct get_impl<0>
{
    template <int N> static T & get(MyTuple<N> & t)
    {
        return t.data;
    }
};

The key here is to have a specialization when K = 0 which extracts the actual element, and to cast up the inheritance hierarchy until you're there. Finally, we slingshot the tuple type deduction through a function template:

template <int K, int N> T & get(MyTuple<N> & t)
{
    return get_impl<K>::get(t);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文