Does the solution of the diamond problem exist for the CRTP?
The code below highlights the problem. An attempt to compile the code results in the following error:
error: cannot convert from pointer to base class 'A<D>' to pointer to derived class 'D' because the base is virtual
{return static_cast<T*>(this);}
I understand the reason for the error (link) and I am looking for an alternative way to resolve the diamond problem (for example, through a modification of the design pattern without the use of virtual inheritance). Thus, I would like to understand if it is possible to create a CRTP-based design pattern that will allow for appropriate implementation of the multiple inheritance without the need to use virtual inheritance.
#include <iostream>
using namespace std;
template<class T>
class A
{
protected:
T* asLeaf(void)
{return static_cast<T*>(this);}
T const* asLeaf(void) const
{return static_cast<T const*>(this);}
double q = 10;
double b = 20;
public:
void print(void)
{
asLeaf()->printImpl();
}
};
template<class T>
class B: virtual public A<T>
{};
template<class T>
class C: virtual public A<T>
{};
class D: public B<D>, public C<D>
{
public:
void printImpl()
{
std::cout << q << " "<< b << std::endl;
}
};
int main()
{
D d;
std::cout << sizeof(d) << std::endl;
d.print();
return 0;
}
This is the second time I am asking the question. Unfortunately, I decided to delete my first attempt at asking the question due to several down votes. If you decide to down vote the question, I will highly appreciate if you state the reason for the down vote in your comments.
Aucun commentaire:
Enregistrer un commentaire