加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何查找参数包的长度?

发布时间:2020-12-16 03:33:59 所属栏目:百科 来源:网络整理
导读:假设我有一个可变参数模板函数 templatetypename... Argsunsigned length(Args... args); 如何使用长度函数找到参数列表的长度? 解决方法 使用sizeof …: templatetypename... Argsconstexpr std::size_t length(Args...){ return sizeof...(Args);} 请注
假设我有一个可变参数模板函数
template<typename... Args>
unsigned length(Args... args);

如何使用长度函数找到参数列表的长度?

解决方法

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

请注意,您不应使用unsigned,而应使用std :: size_t(在< cstddef>中定义).此外,该函数应该是一个常量表达式.

不使用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
}

注意,一切都是完全未经测试的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读