我想Data在矢量中保存一些结构.这些结构通过索引(而不是指针)引用其他结构,以节省内存并使序列化更容易.为了遵循这些索引,我创建了一个类DataView,它为它提供了一个舒适的界面.它看起来像这样:
#include <iostream>
#include <vector>
struct Data
{
int id_next;
int id_prev;
int value;
};
class Foo;
class DataView
{
Foo * foo;
int index;
public:
DataView( Foo * foo_, int index_ )
: foo( foo_ ), index( index_ )
{
}
DataView next() const;
DataView prev() const;
int value() const;
int & value();
int id() const
{
return index;
}
};
class Foo
{
std::vector<Data> data;
public:
friend class DataView;
DataView dataview( int index )
{
return DataView( this, index );
}
Foo()
{
data.resize( 5 );
for ( int i = 0; i < (int)data.size(); i++ )
{
data[i].id_next = (i + 1) % data.size();
data[i].id_prev = (i + 4) % data.size();
data[i].value = i * i;
}
}
void write_cycle( int start_index ) // const
{
DataView seek = dataview( start_index );
do
{
std::cout << "index " << seek.id() << " value " << seek.value() << std::endl;
seek = seek.next();
} while ( seek.id() != start_index );
}
};
DataView DataView::next() const
{
return DataView( foo, foo->data[index].id_next );
}
DataView DataView::prev() const
{
return DataView( foo, foo->data[index].id_prev );
}
int DataView::value() const
{
return foo->data[index].value;
}
int & DataView::value()
{
return foo->data[index].value;
}
int main()
{
Foo foo;
foo.write_cycle( 3 );
foo.dataview( 2 ).value() = 11;
foo.write_cycle( 3 );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我必须区分方法的常量和非常量变体,就会出现问题dataview.事实上,write_cycle应该是const,因为它不会改变任何东西.但是,如果取消注释const限定符,则会出现编译器错误.
错误:将'const Foo'传递为'this'参数会丢弃限定符[-fpermissive]
如何编写DataView包含const或非const foo指针,具体取决于它的构造函数是用const还是非const指针调用的?
你说:
这些结构通过索引(而不是指针)引用其他结构,以节省内存并使序列化更容易.为了遵循这些索引,我创建了一个类
DataView,它为它提供了一个舒适的界面.
这向我表明你不应该支持:
foo.dataview( 2 ).value() = 11;
Run Code Online (Sandbox Code Playgroud)
使用DataView仅读取数据.如果您同意,可以更改DataView为存储a Foo const*.然后你可以摆脱非const版本的DataView::value().
class DataView
{
Foo const* foo;
int index;
public:
DataView( Foo const* foo_, int index_ )
: foo( foo_ ), index( index_ )
{
}
DataView next() const;
DataView prev() const;
int value() const;
// Don't need this.
// int & value();
int id() const
{
return index;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |