【问题标题】:Detect if a container has iterator type or not检测容器是否具有迭代器类型
【发布时间】:2018-05-16 08:21:24
【问题描述】:

考虑以下伪代码:

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

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

【问题讨论】:

  • 如果它是一个STL 容器,那么它有一个迭代器。但是将迭代器作为参数而不是容器通常更灵活/可重用。
  • 是否需要同时支持Container有迭代器类型的情况和没有迭代器类型的情况?你的代码暗示你这样做,但这不是你问的问题。
  • 是的,我想支持这两种情况。我的问题是:确定容器是否具有迭代器类型,在代码 sn-p 中我将其表示为条件。我想这是我问的一个问题。
  • Galik,valarray 是一个容器,因为它包含多个相同类型的元素并且它没有迭代器类型。

标签: c++ templates stl


【解决方案1】:

您使用detection idiom

#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
      }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2023-04-10
    • 2016-05-26
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多