c++ - 我能否获取模板类型的 "iterator",无论该类型是数组还是类似 STL 的容器?

标签 c++ templates iterator c++11

这是我的例子:

template<typename TContainer>
class MyClass
{
public:
   typedef typename SomeUnknownHelper<TContainer>::iterator iterator;
};

std::vector<int>::iterator i = MyClass<std::vector<int>>::iterator;
int *pi = MyClass<int[20]>::iterator;

基本上,我不知道如何编写SomeUnknownHelper

我知道我可以专门化 MyClass 本身,但在我的实际情况中,这会很麻烦,因为类很大。

最佳答案

使用 decltypestd::begin 可以轻松实现这一点:

#include <iterator>
#include <utility>

namespace tricks{
  using std::begin; // fallback for ADL
  template<class C>
  auto adl_begin(C& c) -> decltype(begin(c)); // undefined, not needed
  template<class C>
  auto adl_begin(C const& c) -> decltype(begin(c)); // undefined, not needed
}

template<typename TContainer>
class MyClass
{
public:
   typedef decltype(tricks::adl_begin(std::declval<TContainer>())) iterator;
};

std::vector<int>::iterator i = MyClass<std::vector<int>>::iterator;
int *pi = MyClass<int[20]>::iterator;

更好的选择可能是使用 Boost.Range:

#include <boost/range/metafunctions.hpp>

template<typename TContainer>
class MyClass
{
public:
   typedef typename boost::range_iterator<TContainer>::type iterator;
};

std::vector<int>::iterator i = MyClass<std::vector<int>>::iterator;
int *pi = MyClass<int[20]>::iterator;

关于c++ - 我能否获取模板类型的 "iterator",无论该类型是数组还是类似 STL 的容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9402476/

相关文章:

c++ - 从第 n 个元素开始迭代 vector

c++ - 通过 const_iterator 迭代 std::list

c++ - 如何访问由另一个 API 定义和分配的变量

c++ - 用 int 值初始化 vector <char>

c++ - Linux C++ 编译错误

c++ - 使用右值引用重载模板化可变参数运算符

rust - 发生移动是因为 `*arg` 的类型为 `String` ,该类型未实现 `Copy` 特征

c++ - 什么 C++14 规则禁止 constexpr 函数对数据成员进行赋值?

c++ - 弃用的结构成员 C++

c++ - 有没有办法部分实例化一个c++模板