gpt4 book ai didi

c++ - crtp父访问姐妹类

转载 作者:行者123 更新时间:2023-11-28 07:30:47 25 4
gpt4 key购买 nike

我有一个名为 base 的类。这个类是不可访问的(我的意思是源代码),因为它是第 3 方类。这个类有一个方法,我想从(父)姐妹(比如说叔叔)类访问。

class base {
public:
void do_something() {
std::cout << "base1::do_something" << std::endl;
}
};

我有另一个父类,它是使用 crtp 创建的访问子类的成员:

template<typename crtpT>
class crtp {
public:
void foo() {
std::cout << "crtp::foo" << std::endl;
static_cast<crtpT*>(this)->bar();

//static_cast<crtpT::base_type*>(this)->do_something();
// how do i access base::bar
}
};

最后,继承自两者的子类:

template<typename baseT>
class child : public baseT, public crtp<child<baseT> > {
public:
typedef baseT base_type;

void bar() {
std::cout << "child::bar" << std::endl;
}
};

主要.cpp:

int main(int argc, char* argv[]) {
child<base> ch;
ch.do_something();
ch.foo();
ch.bar();
return 0;
}

现在我的问题是,我需要从我的 crtp 类访问 do_something。这甚至可能吗?

static_cast 将不起作用。我认为在生成 crtp 类时,编译器对基类一无所知。 crtp 类必须是类子类的父类,因为很多其他类都派生自它。否则我可能会使用 delegation to sister-class .


编辑:

我可以在我的 child 体内做第二个 bar 方法,但这不是很好,因为我必须为 base 类中的所有方法编写包装器。

template<typename baseT>
class child : public baseT, public crtp<child<baseT> > {

public:
typedef baseT base_type;

void bar() {
std::cout << "child::bar" << std::endl;
}

void bar2() {
base_type::do_something();
}
};

并调用:

static_cast<crtpT*>(this)->bar2();

最佳答案

static_cast : [expr.static.cast]/11

A prvalue of type “pointer to cv1 B,” where B is a class type, can be converted to a prvalue of type “pointer to cv2 D,” where D is a class derived from B [...]

因此,您需要从crtp<...>* 进行转换给 child 类child*然后你甚至可以使用隐式转换为 base ,例如

crtpT::base_type* p = static_cast<crtpT*>(this);

关于c++ - crtp父访问姐妹类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772552/

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