gpt4 book ai didi

c++ - 在模板类中使用 shared_from_this

转载 作者:IT老高 更新时间:2023-10-28 21:44:44 26 4
gpt4 key购买 nike

我有一个资源管理器,就像 Andrei Alexandrescu 在 Modern C++ Design 一书中提出的那样,它遵循基于策略的设计。不过我遇到了麻烦,因为我的资源管理器需要能够通过 shared_from_this() 向自己提供对托管资源的引用。

我构建了一个最小示例来重现我的问题,结果您可以看到 here .

基本上我有一些托管资源需要引用其管理器:

template <typename T>
class managed_resource
{
typedef std::shared_ptr<manager<T>> manager_ptr;
public:
managed_resource(manager_ptr const & parent)
: parent_(parent)
{
}

/* ... */

private:
manager_ptr parent_;
};

还有一个存储和提供资源的经理:

template <typename Policy>
class manager
: Policy
, std::enable_shared_from_this<manager<Policy>>
{
typedef managed_resource<Policy> resource;
typedef std::shared_ptr<resource> resource_ptr;
public:
resource_ptr get_resource(std::string const & name)
{
Policy & p = *this;
if(p.find(name))
{
return p.get(name);
}
resource_ptr res = std::make_shared<resource>(shared_from_this());
p.store(name, res);
return res;
}
};

如您所见,存储本身是基于策略的。虽然经理确实创建了资源,但策略可以在各种存储信息的方法之间自由决定(例如,它可以选择不存储任何内容并每次都创建新资源)。

这是存储策略的示例:

class map_policy
{
typedef std::shared_ptr<managed_resource<map_policy>> resource_ptr;
typedef std::map<std::string, resource_ptr> resources;

public:
bool find(std::string const & name)
{
resources::iterator res_it = resources_.find(name);
return res_it != resources_.end();
}

resource_ptr get(std::string const & name)
{
resources::iterator res_it = resources_.find(name);
return res_it->second;
}

void store(std::string const & name, resource_ptr const & res)
{
resources_[name] = res;
}

private:
resources resources_;
};

但是我得到一个编译错误:

error: there are no arguments to ‘shared_from_this’ that depend 
on a template parameter, so a declaration of
‘shared_from_this’ must be available
error: ‘std::enable_shared_from_this<manager<map_policy> >’ is
an inaccessible base of ‘manager<map_policy>’

完整的编译输出见 minimal example .

在基于策略的设计中是否不可能使用 std::enable_shared_from_thisshared_from_this()?如果没有,正确的使用方法是什么?

最佳答案

enable_shared_from_this<manager<Policy>>是一个“依赖基类”(它是一个类型取决于模板参数的基类,在这种情况下为 Policy),因此 C++ 的规则说不合格名称查找不在那里,你需要说 this->shared_from_this()std::enable_shared_from_this<manage<Policy>>::shared_from_this()从依赖基中查找成员。

http://gcc.gnu.org/wiki/VerboseDiagnostics#dependent_base了解更多详细信息和其他引用资料的链接。

要修复第二个错误,您需要执行 enable_shared_from_this public 基类,或者当管理器由 shared_ptr 拥有时无法初始化.

关于c++ - 在模板类中使用 shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com