문제

i have a class named base. this class is inaccessable(i mean the sourcecode) since it is a 3rd party class. this class has a method that i want to access from a (parent)sister (let's say uncle) class.

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

i have another parent class which is made by using crtp to access the members of the child class:

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
  }
};

and last, a child class which inherits from both:

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

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

main.cpp:

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

now my problem is, i need to access do_something from my crtp-class. is this even possible?

a static_cast won't work. i think while generating the crtp class the compiler do not know anything about the base class. crtp class have to be a parent of class child, since a lot other classes deriving from it. otherwise i may use a delegation to sister-class.


edit:

i may could do a second bar method inside my child, but this isn't really nice because i have to write wrapper for all the methods from the base class.

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();
  }
};

and call:

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 [...]

Therefore, you need to convert from crtp<...>* to the child class child* and then you can even use an implicit cast to base, e.g.

crtpT::base_type* p = static_cast<crtpT*>(this);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top