我有一个Data类和一个提供访问Data的方法的Wrapper类。WrapperMutable类扩展Wrapper以添加修改Data的方法。
#include <memory>
using namespace std;
class Data {
public:
void update(); // non-const method which modifies internal state of Data
};
class Wrapper
{
public:
Wrapper(shared_ptr<Data const> data) : myData(data) {} // accepts const pointer
// ...bunch of functions providing read-only access to aspects of the Data...
protected:
shared_ptr<Data const> myData; // stores const pointer
};
// Extend Wrapper with methods to modify the wrapped Data.
class WrapperMutable : public Wrapper
{
public:
WrapperMutable(shared_ptr<Data> data) : Wrapper(data) {}
// ERROR: invoking non-const method on const object:
void updateData() { myData->update(); }
};当然,问题出在包装的Data对象的const-ness上,这意味着WrapperMutable不能修改它。
我考虑将Wrapper更改为接受和存储非const Data,但通常客户端本身只能访问const Data,因此它们将被迫使用const_cast或copy来创建Wrapper。
所以我能做到这一点的唯一方法是在WrapperMutable类中保留一个额外的非const指针,并在可变上下文中使用它:
class WrapperMutable : public Wrapper
{
public:
WrapperMutable(shared_ptr<Data> data) : Wrapper(data), myMutableData(data) {}
// Use myMutableData instead of the const myData
void updateData() { myMutableData->update(); }
private:
shared_ptr<Data> myMutableData; // non-const pointer to the same Data as in Wrapper
};有没有更好的方法?显然,从Wrapper派生WrapperMutable是我的问题的根源,但我也不想在WrapperMutable中重新实现Wrapper的所有方法。
发布于 2015-11-10 21:38:39
#include <memory>
using namespace std;
class Data {
public:
void update() {} // non-const method which modifies internal state of Data
};
//Basic wrapper
template <typename D>
class BaseWrapper {
public:
BaseWrapper(shared_ptr<D> data) : myData(data) {}
protected:
shared_ptr<D> myData;
};
template <typename D, bool const = std::is_const<D>::value>
class Wrapper : public BaseWrapper<D>
{
};
//Const-Version
template <typename D>
class Wrapper<D, true> : public BaseWrapper<D>
{
public:
Wrapper(shared_ptr<D> data) : BaseWrapper(data) {}
};
//Non-Const-Version
template <typename D>
class Wrapper<D, false> : public BaseWrapper<D>
{
public:
Wrapper(shared_ptr<D> data) : BaseWrapper(data) {}
void updateData() { myData->update(); }
};
int main()
{
Wrapper<Data> a(nullptr);
Wrapper<const Data> b(nullptr);
a.updateData();
b.updateData();//error C2039: 'updateData': is not a member of 'Wrapper<const Data,true>'
}https://stackoverflow.com/questions/33629801
复制相似问题