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

Joa*_*ald 6 c++ templates variadic-templates fold-expression c++17

给定一个可变参数模板参数包,我想检查使用inline constexpr bool和折叠表达式给出的所有类型是否唯一.我喜欢这样的东西:

template<class... T>
inline static constexpr bool is_unique = (... && (!is_one_of<T, ...>));
Run Code Online (Sandbox Code Playgroud)

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

Vit*_*meo 10

你的方法并不真正起作用,因为is_one_of需要使用类型调用,T而所有其余类型都不包括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...>
>{};   
Run Code Online (Sandbox Code Playgroud)

用法:

static_assert(is_unique<>);
static_assert(is_unique<int>);
static_assert(is_unique<int, float, double>);
static_assert(!is_unique<int, float, double, int>);
Run Code Online (Sandbox Code Playgroud)

wandbox.org上的实例


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

  • 可以用〜(!is_same_v <T0,Rest> && ...)&& is_unique <Rest ...>`的主体简化为`T0,Rest ...`? (3认同)
  • 虽然另一个答案提供了一种方法,可以根据我的需要使用折叠表达式和constexpr bool,它会附带很多警告,但仍然需要我想要的其他结构,所以你的回答是"你不能这样做"更合适.谢谢! (2认同)