简体   繁体   English

使用可变参数模板计算元组大小时得到错误的大小

[英]Getting wrong size when calculating tuple size using variadic templates

I am trying to write my own implementation of the tuple_size function before looking how it is implemented in C++ library. 在查看如何在C ++库中实现它之前,我尝试编写自己的tuple_size函数实现。 The problem that I am getting right now is that I am getting wrong answer (1) and I do not see any preconditions for that. 我现在遇到的问题是答案(1)错误,并且看不到任何先决条件。 Appreciate any help. 感谢任何帮助。

#include <iostream>

using namespace std;
namespace tuple_helpers
{
    template <typename... Args>
    struct _tuple_size;

    template<typename T, typename... Args>
    class _tuple_size<T, Args...>
    {
    public:
        constexpr static size_t __size()
        {
            return _tuple_size<Args...>::__size() + 1;
        }
    };

    template<>
    class _tuple_size<>
    {
    public:
        constexpr static size_t __size()
        {
            return 0;
        }
    };

    template<typename T>
    class tuple_size
    {
    public:
        enum { value = _tuple_size<T>::__size() };
    };
}

int main()
{
    using MyTuple = tuple<int, string, bool, double>;
    cout << "Size of the tuple is: " << tuple_helpers::tuple_size<MyTuple>::value;

    return 0;
}

_tuple_size<ARGS>::__size() is like sizeof...(ARGS) . _tuple_size<ARGS>::__size()就像sizeof...(ARGS) Since you only pass one template parameter, this will always be 1. 由于您仅传递一个模板参数,因此该参数始终为1。

You need to actually use the template parameters of the template: 您需要实际使用模板的模板参数:

template<typename T>
class tuple_size;

template<typename... Args>
class tuple_size<std::tuple<Args...>> {
public:
    enum { value = _tuple_size<Args...>::__size() };
};

// Or to work with any tuple-like classes
template<typename... Args, template<typename...> class Tuple>
class tuple_size<Tuple<Args...>> {
public:
    enum { value = _tuple_size<Args...>::__size() };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM