C++ 通过自定义模板化迭代器使不可iterable容器适应于迭代
我有一些类,由于各种原因超出了本文讨论的范围,我无法修改它们(忽略了无关的实现细节): (我正在处理许多类似的'Foo'和'Bar'类,它们都是从其他地方生成的代码以及我不想子类化的东西,等等。) [编辑:澄清-尽管有许多类似的'Foo'和'Bar'类,但可以保证每个“外部”类都有getter和size方法。根据每个“外部”包含的“内部”类型,只有getter方法名称和返回类型不同 因此,如果我有包含qux实例的Baz,那么将有qux&Baz::get_qux(size\t index)和size_t Baz::size_qux() 考虑到Bar类的设计,您无法在STL算法中轻松使用它(例如,for_each、find_if等),必须执行命令式循环,而不是采用函数式方法(我喜欢后者的原因也不在本讨论的范围内):C++ 通过自定义模板化迭代器使不可iterable容器适应于迭代,c++,templates,C++,Templates,我有一些类,由于各种原因超出了本文讨论的范围,我无法修改它们(忽略了无关的实现细节): (我正在处理许多类似的'Foo'和'Bar'类,它们都是从其他地方生成的代码以及我不想子类化的东西,等等。) [编辑:澄清-尽管有许多类似的'Foo'和'Bar'类,但可以保证每个“外部”类都有getter和size方法。根据每个“外部”包含的“内部”类型,只有getter方法名称和返回类型不同 因此,如果我有包含qux实例的Baz,那么将有qux&Baz::get_qux(size\t index)和siz
条b;
size_t numFoo=b.size_foo();
for(int fooIdx=0;fooIdx
所以。。。我从未创建过自定义迭代器,在阅读了S.O.上关于迭代器特性等的各种问题/答案后,我提出了这个(目前还不成熟的)“解决方案”:
首先,自定义迭代器机制(注意:“function”和“bind”的所有用法都来自MSVC9中的std::tr1):
//迭代器机制。。。
模板
类ContainerIterator:public std::iterator{
公众:
typedef函数func_type;
ContainerIterator(const ContainerIterator&other):mFunc(other.mFunc),mIndex(other.mIndex){}
ContainerInterator&operator++(){++mIndex;返回*this;}
布尔运算符==(常量容器运算符和其他){
返回((mFunc.target()==other.mFunc.target())&&&(mIndex==other.mIndex));
}
bool运算符!=(const ContainerIterator&other){return!(*this==other);}
TInner&运算符*(){return mFunc(mIndex);}
私人:
模板
朋友级集装箱代理;
容器运算符(func_type func,size_t index=0):mFunc(func),mIndex(index){
函数mFunc;
mIndex的尺寸;
};
接下来是获取表示内部容器开始和结束的有效迭代器的机制:
// Proxy(?) to the outer class instance, providing a way to get begin() and end()
// iterators to the inner contained instances...
template <typename TOuter, typename TInner>
class ContainerProxy {
public:
typedef function<TInner& (size_t)> access_func_type;
typedef function<size_t ()> size_func_type;
typedef ContainerIterator<TOuter, TInner> iter_type;
ContainerProxy(access_func_type accessFunc, size_func_type sizeFunc) : mAccessFunc(accessFunc), mSizeFunc(sizeFunc) {}
iter_type begin() const {
size_t numItems = mSizeFunc();
if (0 == numItems) return end();
else return ContainerIterator<TOuter, TInner>(mAccessFunc, 0);
}
iter_type end() const {
size_t numItems = mSizeFunc();
return ContainerIterator<TOuter, TInner>(mAccessFunc, numItems);
}
private:
access_func_type mAccessFunc;
size_func_type mSizeFunc;
};
// incomplete general case
template <typename TOuter> struct LegacyContainerTraits;
// Specialization for 'Bar'
template <> struct LegacyContainerTraits<Bar>
{
// The inner type of 'Bar' is 'Foo'
typedef Foo inner_type;
static size_t get_size(Bar const& outer) {return outer.size_foo();}
static Foo& get_element(Bar const& outer, size_t index) {
return outer.get_foo(index);
}
};
// Specialization for Baz
template <> struct LegacyContainerTraits<Baz>
{
// The inner type of 'Baz' is 'Quux'
typedef Quux inner_type;
static size_t get_size(Baz const& outer) {return outer.size_quux();}
static Quux& get_element(Baz const& outer, size_t index) {
return outer.get_quux(index);
}
};
//代理(?)到外部类实例,提供获取begin()和end()的方法
//内部包含实例的迭代器。。。
模板
类容器代理{
公众:
typedef函数访问函数类型;
typedef函数大小函数类型;
类型DEF集装箱运输机iter_类型;
ContainerProxy(access\u func\u type accessFunc,size\u func\u type sizeFunc):MacAccessFunc(accessFunc),mSizeFunc(sizeFunc){}
iter_类型begin()常量{
size_t numItems=mSizeFunc();
如果(0==numItems)返回end();
else返回容器运算符(mAccessFunc,0);
}
iter_类型end()常量{
size_t numItems=mSizeFunc();
返回容器运算符(mAccessFunc,numItems);
}
私人:
访问函数类型mAccessFunc;
大小函数类型mSizeFunc;
};
我可以以下列方式使用这些类:
// Sample function object for taking action on an LMX inner class instance yielded
// by iteration...
template <typename TInner>
class SomeTInnerFunctor {
public:
void operator()(const TInner& inner) {
/* ... whatever ... */
}
};
// Example of iterating over an outer class instance's inner container...
Bar b; /* assume populated which contained items ... */
ContainerProxy<Bar, Foo> bProxy(
bind(&Bar::get_foo, b, _1),
bind(&Bar::size_foo, b));
for_each(bProxy.begin(), bProxy.end(), SomeTInnerFunctor<Foo>());
//用于对LMX内部类实例执行操作的示例函数对象
//通过迭代。。。
模板
类SomeTInnerFunctor{
公众:
void运算符()(常量TInner和内部){
/*……不管怎样*/
}
};
//迭代外部类实例的内部容器的示例。。。
b栏;/*假设已填充哪些包含项*/
集装箱代理(
绑定(&Bar::get_foo,b,_1),
绑定(&Bar::size_foo,b));
对于每个(bProxy.begin()、bProxy.end()、SomeTInnerFunctor());
根据经验,此解决方案功能正确(减去为简洁起见编辑上述内容时可能引入的任何复制/粘贴或打字错误)
最后,实际问题是:
我不喜欢要求调用方使用bind()和_1占位符等。他们真正关心的是:外部类型,内部类型,外部类型获取内部实例的方法,外部类型获取内部实例计数的方法
有没有办法在模板类的主体中“隐藏”绑定?我无法找到一种方法来分别为类型和内部方法提供模板参数
谢谢David您可以定义一个助手模板结构来隐藏与Foo和Bar交互的实际机制。然后针对每个容器进行专门化:
// Proxy(?) to the outer class instance, providing a way to get begin() and end()
// iterators to the inner contained instances...
template <typename TOuter, typename TInner>
class ContainerProxy {
public:
typedef function<TInner& (size_t)> access_func_type;
typedef function<size_t ()> size_func_type;
typedef ContainerIterator<TOuter, TInner> iter_type;
ContainerProxy(access_func_type accessFunc, size_func_type sizeFunc) : mAccessFunc(accessFunc), mSizeFunc(sizeFunc) {}
iter_type begin() const {
size_t numItems = mSizeFunc();
if (0 == numItems) return end();
else return ContainerIterator<TOuter, TInner>(mAccessFunc, 0);
}
iter_type end() const {
size_t numItems = mSizeFunc();
return ContainerIterator<TOuter, TInner>(mAccessFunc, numItems);
}
private:
access_func_type mAccessFunc;
size_func_type mSizeFunc;
};
// incomplete general case
template <typename TOuter> struct LegacyContainerTraits;
// Specialization for 'Bar'
template <> struct LegacyContainerTraits<Bar>
{
// The inner type of 'Bar' is 'Foo'
typedef Foo inner_type;
static size_t get_size(Bar const& outer) {return outer.size_foo();}
static Foo& get_element(Bar const& outer, size_t index) {
return outer.get_foo(index);
}
};
// Specialization for Baz
template <> struct LegacyContainerTraits<Baz>
{
// The inner type of 'Baz' is 'Quux'
typedef Quux inner_type;
static size_t get_size(Baz const& outer) {return outer.size_quux();}
static Quux& get_element(Baz const& outer, size_t index) {
return outer.get_quux(index);
}
};
然后,您可以在循环或算法中相当容易地使用自由函数。即使在基于范围的for循环中:
Bar b=...;
for (auto it=begin(b); it!=end(b); ++it) {...}
for (auto f : b) {...}
std::for_each(begin(b), end(b), ...);
更充实的版本:或者,如果函数具有可预测的签名,则始终可以将函数本身作为模板参数:
template <typename TOuter, typename TInner,
TInner& (TOuter::*getfunc)(size_t )>
class ContainerIterator
{
public:
//...
TInner& operator*() {return mContainerRef.*getfunc(mIndex);}
//...
};
template <typename TOuter, typename TInner,
size_t (TOuter::*sizefunc)(),
TInner& (TOuter::*getfunc)(size_t )>
class ContainerProxy
{
public:
//...
ContainerIterator<TOuter, TInner, getfunc> end() {
return ContainerIterator<TOuter, TInner, getfunc>
(mContainerRef,
mContainerRef.*sizefunc());
}
//...
};
int main()
{
Bar b;
ContainerProxy<Bar, Foo, &Bar::size_foo, &Bar::get_foo> proxy(b);
std::for_each(proxy.begin(), proxy.end(), /*...*/);
}
这里是Managu解决方案变体的完整实现。 (我知道我还没有实现获得真正的随机访问迭代器所需的所有迭代器函数..实现其余的是读者的练习。)
#包括
#包括
#包括
福班{
公众:
富(国际ii):i(ii){}
Foo():i(){}
int i;
};
分类栏{
公众:
Bar():f1(1),f2(2),f3(3){}
Foo&get\u Foo(尺码i){
如果(i==0)返回f1;
如果(i==1)返回f2;
返回f3;
}
size_t n_foo()常量{return 3;}
富f1;
Foo-f2;
富f3;
};
模板<
内部类型名,
外部类型名,
尺寸(外部::*计数器)()常数,
内部和(外部::*存取器)(尺寸>
类容器代理{
公众:
ContainerProxy(外部*o):外部(o){}
外*外;
结构迭代器{
typedef std::随机访问迭代器标记迭代器类别;
类型定义内部值\u类型;
typedef ptrdiff_t difference_type;
typedef内部*指针;
typedef内部&
Bar b=...;
for (auto it=begin(b); it!=end(b); ++it) {...}
for (auto f : b) {...}
std::for_each(begin(b), end(b), ...);
template <typename TOuter, typename TInner,
TInner& (TOuter::*getfunc)(size_t )>
class ContainerIterator
{
public:
//...
TInner& operator*() {return mContainerRef.*getfunc(mIndex);}
//...
};
template <typename TOuter, typename TInner,
size_t (TOuter::*sizefunc)(),
TInner& (TOuter::*getfunc)(size_t )>
class ContainerProxy
{
public:
//...
ContainerIterator<TOuter, TInner, getfunc> end() {
return ContainerIterator<TOuter, TInner, getfunc>
(mContainerRef,
mContainerRef.*sizefunc());
}
//...
};
int main()
{
Bar b;
ContainerProxy<Bar, Foo, &Bar::size_foo, &Bar::get_foo> proxy(b);
std::for_each(proxy.begin(), proxy.end(), /*...*/);
}
template <typename TOuter, typename TInner>
struct ContainerIterator : public std::iterator<std::input_iterator_tag, TInner>
{
TOuter& mContainerRef;
//...
typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
getfunc_type mGetfunc;
ContainerIterator(TOuter& containerRef, size_t index, getfunc_type const& getFunc)
/* ... */ {}
TInner& operator*() {return mGetfunc(&mContainerRef, mIndex);}
ContainerIterator<TOuter, TInner>& operator++() {++mIndex; return *this;}
// ...
};
template <typename TOuter, typename TInner>
struct ContainerProxy
{
TOuter& mContainerRef;
typedef std::function<size_t (TOuter*)> sizefunc_type;
sizefunc_type mSizefunc;
typedef std::function<TInner& (TOuter*, size_t)> getfunc_type;
getfunc_type mGetfunc;
ContainerProxy(TOuter& containerRef, sizefunc_type sizefunc, getfunc_type getfunc)
// ...
{
}
// ...
ContainerIterator<TOuter, TInner> end() const
{
return ContainerIterator<TOuter, TInner>(mContainerRef,
mSizefunc(&mContainerRef),
mGetfunc);
}
};
int main()
{
Bar b=...;
ContainerProxy<Bar, Foo> proxy(b, &Bar::size_foo, &Bar::get_foo);
std::for_each(proxy.begin(), proxy.end(), /*...*/);
}
#include <vector>
#include <iostream>
#include <iterator>
class Foo {
public:
Foo( int ii ) : i(ii) {}
Foo() : i() {}
int i;
};
class Bar {
public:
Bar() : f1(1), f2(2), f3(3) {}
Foo& get_foo( size_t i ) {
if(i==0) return f1;
if(i==1) return f2;
return f3;
}
size_t n_foo() const { return 3; }
Foo f1;
Foo f2;
Foo f3;
};
template<
typename INNER,
typename OUTER,
size_t(OUTER::*COUNTER)() const,
INNER&(OUTER::*ACCESSOR)(size_t) >
class ContainerProxy {
public:
ContainerProxy( OUTER * o ) : outer(o) {}
OUTER * outer;
struct Iterator {
typedef std::random_access_iterator_tag iterator_category;
typedef INNER value_type;
typedef ptrdiff_t difference_type;
typedef INNER* pointer;
typedef INNER& reference;
ContainerProxy * container;
size_t index;
Iterator( ContainerProxy * c, size_t i ) : container(c), index(i) {}
Iterator& operator++() { index++; return *this; }
INNER& operator*() { return (container->outer->*ACCESSOR)(index); }
difference_type operator-( const Iterator other ) const { return index-other.index; }
};
Iterator begin() { return Iterator(this,0); }
Iterator end() { return Iterator(this, (outer->*COUNTER)() ); }
};
int main() {
Bar bar;
ContainerProxy<Foo,Bar, &Bar::n_foo, &Bar::get_foo> container(&bar);
std::vector<Foo> v(3);
std::copy( container.begin(), container.end(), v.begin() );
std::cout<<v[0].i<<std::endl;
std::cout<<v[1].i<<std::endl;
std::cout<<v[2].i<<std::endl;
}