我可以得到“迭代器”吗?对于模板类型,无论该类型是数组还是类似STL的容器? [英] Can I get the "iterator" for a template type, regardless if that type is an array or STL-like container?

查看:182
本文介绍了我可以得到“迭代器”吗?对于模板类型,无论该类型是数组还是类似STL的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的例子:

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

Basically, I don't know how to write SomeUnknownHelper.

我知道我可以专攻 MyClass 本身,但在我的实际案例中,它会是麻烦,因为班级很大。

I know I could specialize MyClass itself, but in my real-world case it would be a hassle because the class is large.

推荐答案

这很容易用 decltype std :: 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:

An even better option might be using 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;

这篇关于我可以得到“迭代器”吗?对于模板类型,无论该类型是数组还是类似STL的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆