检测容器是否具有迭代器类型

问题描述 投票:0回答:2

考虑以下伪代码:

template<class Container>
int some_function(const Container& container)
{
      if (container has iterator) { // 
            // get an element by its iterator
      } else {
            // do another action
      }
}

因此,我们有一个函数模板,它采用容器类型(例如,向量、列表、valarray 或其他类型)。是否可以确定(运行时)给定容器是否具有迭代器类型?编译时间?

c++ templates stl
2个回答
3
投票

您使用了检测惯用语

#include<experimental/type_traits>

template<typename T>
using iterator_t = typename T::iterator;

template<typename T>
constexpr bool has_iterator = std::experimental::is_detected_v<iterator_t, T>;

template<class Container>
int some_function(const Container& container)
{
      if constexpr (has_iterator<Container>) {
            // get an element by its iterator
      } else {
            // do another action
      }
}

0
投票

可以实现自定义类型特征

has_iterator
,如果类型
T
定义
iterator
,则其计算结果为 true。

示例:

namespace detail {
  template <typename, typename = void>
  struct has_iterator
   : public std::false_type {};

  template <typename T>
  struct has_iterator<T, std::void_t<typename T::iterator>>
   : public std::true_type {};
}

template <typename T>
struct has_Iterator
 : public detail::has_iterator<T> {};

template <typename T>
inline constexpr bool has_iterator_v = has_iterator<T>::value;

即使

std::void_t
类型特征仅从 C++17 起可用,也可以通过以下方式重新实现它。

示例:

template <typename...>
using void_t = void;
© www.soinside.com 2019 - 2024. All rights reserved.