这是我的例子:
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.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/