首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过扩展添加可变性

通过扩展添加可变性
EN

Stack Overflow用户
提问于 2015-11-10 20:17:54
回答 4查看 80关注 0票数 3

我有一个Data类和一个提供访问Data的方法的Wrapper类。WrapperMutable类扩展Wrapper以添加修改Data的方法。

代码语言:javascript
复制
#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指针,并在可变上下文中使用它:

代码语言:javascript
复制
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的所有方法。

EN

Stack Overflow用户

发布于 2015-11-10 21:38:39

代码语言:javascript
复制
#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>'
}
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33629801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档