How to find the length of a parameter pack?

前端 未结 1 1565
野的像风
野的像风 2021-01-05 06:32

Suppose I have a variadic template function like

template
unsigned length(Args... args);

How do I find the length o

相关标签:
1条回答
  • 2021-01-05 07:35

    Use sizeof...:

    template<typename... Args>
    constexpr std::size_t length(Args...)
    {
        return sizeof...(Args);
    }
    

    Note you shouldn't be using unsigned, but std::size_t (defined in <cstddef>). Also, the function should be a constant expression.


    Without using sizeof...:

    namespace detail
    {
        template<typename T>
        constexpr std::size_t length(void)
        {
            return 1; // length of 1 element
        }
    
        template<typename T, typename... Args>
        constexpr std::size_t length(void)
        {
            return 1 + length<Args...>(); // length of one element + rest
        }
    }
    
    template<typename... Args>
    constexpr std::size_t length(Args...)
    {
        return detail::length<Args...>(); // length of all elements
    }
    

    Note, everything is completely untested.

    0 讨论(0)
提交回复
热议问题