gpt4 book ai didi

c++ - 检查模板参数是否在同质参数包中出现两次以上

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:21 25 4
gpt4 key购买 nike

我需要检查传递给函数的任何参数是否出现了两次以上。本质上,我想要以下行为

appearance<0,1,0,1>::value // should return true
appearance<2,0,1,2,2>::value // should return false
appearance<5,5,5>::value // should return false

我知道有一个关于 finding the number of uniques 的问题,但它没有回答我的问题,因为例如返回该问题的解决方案

no_unique<0,1,0,1,0,1>::value // returns 2

但是没有说参数是出现一次、两次还是三次。

如何在 C++11 中实现这一点?

最佳答案

效率不高,但您可以使用以下内容:

#include <algorithm>
#include <type_traits>

template <size_t S, size_t... Sizes>
struct count;

template <size_t S>
struct count<S>: std::integral_constant<size_t, 0> {};

template <size_t S1, size_t... Sizes>
struct count<S1, S1, Sizes...>:
std::integral_constant<size_t, 1 + count<S1, Sizes...>{}> {};

template <size_t S1, size_t S2, size_t... Sizes>
struct count<S1, S2, Sizes...>:
count<S1, Sizes...> {};

template <size_t...>
struct max_count;

template <>
struct max_count<>: std::integral_constant<size_t, 0> { };

template <size_t S, size_t... Sizes>
struct max_count<S, Sizes...>:
std::integral_constant<size_t, std::max(1 + count<S, Sizes...>{},
max_count<Sizes...>::value)> { };

template <size_t... Sizes>
struct no_more_than_two: std::integral_constant<bool, max_count<Sizes...>{} <= 2> { };

static_assert(no_more_than_two<0,1,0,1>{}, "");
static_assert(!no_more_than_two<2,0,1,2,2>{}, "");
static_assert(!no_more_than_two<5,5,5>{}, "");

您首先检索任何值的最大出现次数,然后将其与 2 进行比较。

如果您只有 C++11(不是 C++14),请将 std::max 替换为自定义 ct_max:

template <typename T>
constexpr const T& ct_max(T const& t1, T const& t2) {
return t1 < t2 ? t2 : t1;
}

关于c++ - 检查模板参数是否在同质参数包中出现两次以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com