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

c – 使用折叠表达式检查可变参数模板参数是否唯一

发布时间:2020-12-16 03:24:10 所属栏目:百科 来源:网络整理
导读:给定一个可变参数模板参数包,我想检查给定的所有类型是否使用内联constexpr bool和 fold expressions是唯一的.我是这样的: templateclass... Tinline static constexpr bool is_unique = (... (!is_one_ofT,...)); 其中is_one_of是一个正常工作的类似bool.
给定一个可变参数模板参数包,我想检查给定的所有类型是否使用内联constexpr bool和 fold expressions是唯一的.我是这样的:
template<class... T>
inline static constexpr bool is_unique = (... && (!is_one_of<T,...>));

其中is_one_of是一个正常工作的类似bool.
但是无论我将什么放入is_one_of,这一行都无法编译.甚至可以使用折叠表达式来完成,还是我需要为此目的使用常规结构?

解决方法

你的方法并不真正有效,因为需要使用类型T调用is_one_of,而不包括T的所有其余类型.没有办法在单个参数包中使用折叠表达式表达.我建议使用专业化:
template <typename...>
inline constexpr auto is_unique = std::true_type{};

template <typename T,typename... Rest>
inline constexpr auto is_unique<T,Rest...> = std::bool_constant<
    (!std::is_same_v<T,Rest> && ...) && is_unique<Rest...>
>{};

用法:

static_assert(is_unique<>);
static_assert(is_unique<int>);
static_assert(is_unique<int,float,double>);
static_assert(!is_unique<int,double,int>);

live example on wandbox.org

(感谢Barry的简化,使用折叠表达式.)

(编辑:李大同)

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

    推荐文章
      热点阅读