使用折叠表达式检查可变参数模板参数是否唯一 [英] Checking if variadic template parameters are unique using fold expressions

查看:47
本文介绍了使用折叠表达式检查可变参数模板参数是否唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到可变参数模板参数包,我想使用 inline constexpr bool

Given a variadic template parameter pack, I want to check if all types given to it are unique using an inline constexpr bool and fold expressions. I trie something like this:

template<class... T>
inline static constexpr bool is_unique = (... && (!is_one_of<T, ...>));

其中 is_one_of 是类似的布尔变量,可以正常工作.但是,无论我输入is_one_of是什么,该行都不会编译.甚至可以使用折叠表达式来完成此操作,还是为此目的需要使用正则结构吗?

Where is_one_of is a similar bool that works correctly. But this line doesn't compile regardless of what I put into is_one_of. Can this even be done using fold expressions, or do I need to use a regular struct for this purpose?

推荐答案

您的方法并没有真正起作用,因为需要使用类型为 T 的所有类型调用 is_one_of 其余类型不包括 T .无法通过单个参数包上的 fold表达式来表达这一点.我建议改用专业化:

You approach doesn't really work because is_one_of needs to be called with a type T and all the remaining types not including T. There's no way of expressing that with a fold expression over a single parameter pack. I suggest using specialization instead:

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, float, double, int>);

在wandbox.org上的在线示例

(感谢 Barry 使用 fold表达式的简化.)

这篇关于使用折叠表达式检查可变参数模板参数是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆