gpt4 book ai didi

c++ - CRTP 中 shared_ptr 的隐式向下转换

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:16 25 4
gpt4 key购买 nike

我构建了一个与 CRTP 一起用于静态多态性的接口(interface)类和一个具有该接口(interface)的 shared_ptr 的客户端类。我想从客户端返回 shared_ptr 到实现,这是我可以(安全地?)通过客户端内的 static_pointer_cast 完成的事情。有没有办法允许从 shared_ptr 到接口(interface)到 shared_ptr 到实现的隐式向下转换?

template<class Implementation>
struct Interface {
int foo() { return static_cast<Implementation*>(this)->fooimpl();}
};

template<class Implementation>
struct Client {
Client(std::shared_ptr<Implementation> const & pt) : pt_{pt} {}
std::shared_ptr<Interface<Implementation>> pt_;
std::shared_ptr<Implementation> getPt() {
//Can I avoid this static_pointer_cast?<
return std::static_pointer_cast<Implementation>(pt_);
}
};

避免所有这些困惑的一个可能的解决方案是在 Client 类中保留一个指向 Implementation 的 shared_ptr。然而,通过这种方式,我没有在任何地方说客户端中的实现具有接口(interface)。


template<class Implementation>
struct Client {
Client(std::shared_ptr<Implementation> const & pt) : pt_{pt} {}
std::shared_ptr<Implementation> pt_;
std::shared_ptr<Implementation> getPt() { return pt_;}
};

最佳答案

Is there a way to allow an implicit downcasting from the shared_ptr to Interface to a shared_ptr to Implementation?

简单的回答:不!由于编译器不知道“反向”继承,它可以直接支持它。 CRTP 是解决潜在问题的通用模式。这里的向下转换是手工编码的,但隐藏在 CRTP 实现的接口(interface)后面。

The CRTP is because I want Client to use foo() and at the same time independent of the implementation

当您将其作为编译时实现获得时,它目前并不是真正独立的。如果你想指向那种 CRTP 类型的东西,你会看到最新的。

The shared_ptr is because the Implementation may be shared among Clients

你的想法有循环问题!

如果您按照示例中给出的方式编写:

模板结构客户{ 客户端(std::shared_ptr const & pt):pt_{pt} {} std::shared_ptr pt_; std::shared_ptr getPt() { 返回 pt_;}};

调用getPt() 的代码必须知道返回指针的类型!即使您使用 auto,您也会获得返回指针的类型。因此,您根本无法从您的使用代码中隐藏它。

I ended up just putting a shared_ptr to the Implementation as class member and added a "static_assert + is_base_of " to insure this.

好像也是循环问题。

如果你写:

template < typename T>
class CRTP: public T
{
public:
void Check()
{
static_assert( std::is_base_of_v < T, CRTP<T> > );
}

};

class A {};

int main()
{
CRTP<A> x;
x.Check();
}

断言在这里有什么帮助?您在“class CRTP: public T”上方写了 4 行只是一个检查。对我来说,这毫无意义。

除了简单地使用 CRTP,我仍然不知道你想要实现什么。

关于c++ - CRTP 中 shared_ptr 的隐式向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57123607/

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