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)
(感谢Barry使用折叠表达式的简化.)