How to find the length of a parameter pack?

前端 未结 1 1585
野的像风
野的像风 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
    constexpr std::size_t length(Args...)
    {
        return sizeof...(Args);
    }
    

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


    Without using sizeof...:

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

    Note, everything is completely untested.

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