gpt4 book ai didi

c++ - 匹配可迭代类型(具有 begin()/end() 的数组和类)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:20 25 4
gpt4 key购买 nike

<分区>

我写了类型特征,比如可以用来测试给定类型是否“可迭代”的类。对于数组(对于 T[N],而不是对于 T[])和具有 begin 的类来说都是如此>end 方法返回看起来像迭代器的东西。我想知道是否可以做得比我做的更简洁/更简单?

特别是 impl 命名空间中的东西看起来有点迂回/hacky。这一切在我看来都有点难看。有关使用它并可以用 g++ 和 clang++ 编译的示例,请参见:https://gist.github.com/panzi/869728c9879dcd4fffa8

template<typename T>
struct is_iterator {
private:
template<typename I> static constexpr auto test(void*)
-> decltype(
*std::declval<const I>(),
std::declval<const I>() == std::declval<const I>(),
std::declval<const I>() != std::declval<const I>(),
++ (*std::declval<I*>()),
(*std::declval<I*>()) ++,
std::true_type()) { return std::true_type(); }

template<typename I> static constexpr std::false_type test(...) { return std::false_type(); }

public:
static constexpr const bool value = std::is_same<decltype(test<T>(0)), std::true_type>::value;
};

namespace impl {
// implementation details

template<typename T>
struct has_iterable_methods {
private:

template<typename C> static constexpr auto test(void*)
-> decltype(
std::declval<C>().begin(),
std::declval<C>().end(),
std::true_type()) { return std::true_type(); }

template<typename C> static constexpr std::false_type test(...) { return std::false_type(); }

public:
static constexpr const bool value = std::is_same<decltype(test<T>(0)), std::true_type>::value;
};

template<typename T, bool HasIterableMethods>
struct returns_iterators : public std::false_type {};

template<typename T>
struct returns_iterators<T, true> {
typedef decltype(std::declval<T>().begin()) begin_type;
typedef decltype(std::declval<T>().end()) end_type;

static constexpr const bool value =
std::is_same<begin_type, end_type>::value &&
is_iterator<begin_type>::value;
};
}

template<typename T>
struct is_iterable : public std::integral_constant<
bool,
impl::returns_iterators<
typename std::remove_const<T>::type,
impl::has_iterable_methods<typename std::remove_const<T>::type>::value>::value> {};

template<typename T, std::size_t N>
struct is_iterable<T[N]> : public std::true_type {};

template<typename T>
struct is_iterable<T*> : public std::false_type {};

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