How to find the length of a parameter pack?

百般思念 提交于 2019-12-30 06:35:27

问题


Suppose I have a variadic template function like

template<typename... Args>
unsigned length(Args... args);

How do I find the length of the parameter list using the length function ?


回答1:


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.



来源:https://stackoverflow.com/questions/2770474/how-to-find-the-length-of-a-parameter-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!