我能否获取模板类型的"iterator",无论该类型是数组还是类似 STL 的容器?
Can I get the "iterator" for a template type, regardless if that type is an array or STL-like container?
下面是我的例子:
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
本身,但在现实世界中,这会很麻烦,因为类很大。
使用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。范围:
#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;
这只是一个单独的专业化,那会有多糟糕?
template <typename T> struct ContainerTrait
{
typedef typename T::iterator iterator;
typedef typename T::const_iterator const_iterator;
};
template <typename T, unsigned int N> struct ContainerTrait<T[N]>
{
typedef T * iterator;
typedef T const * const_iterator;
};
或者,您可以使用免费的std::begin
/std::end
和auto
:
auto it = std::begin(x); // x could be vector<int> or float[10]...
相关文章:
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 类型数组?
- 如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?
- 将基本类型数组中的内存重新用于不同(但仍然是基本)类型的数组合法吗
- 在C++中返回基元类型数组(Java比较)
- 如何返回 QVariant 类型数组
- 如何在本机 c++ jni 中实现 java 类型数组
- 模板类型数组的模板类型数组
- 如何确定未知类型数组的索引是否为空
- 复杂类型数组的静态初始化
- 访问基类型数组成员(Int-to-type习惯用法)
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较
- 如何在C 中制作结构类型数组
- 如何创建结构类型数组的地图对象
- C++类类型数组
- C++中的Matlab类型数组
- 节点C++插件 - 当类型数组(Float32Array)作为参数传递时,如何访问它?
- 如何将二维字符类型数组逐行保存到 c 中的.txt文件中
- C++:用户定义的类型数组出错
- 在双精度类型数组中使用 memset()