Vin*_*ent 5 c++ templates class c++11
考虑以下设计:
template <class SecondType>
struct First
{
SecondType* _ptr;
};
template <class FirstType>
struct Second
{
FirstType* _ptr;
};
Run Code Online (Sandbox Code Playgroud)
其中First类型有一个指向类型的指针,Second反之亦然。问题是我不能声明这一点,因为它们是相互依赖的,我应该声明First<Second<First<Second...>>>.
如何解决这个问题呢 ?
也许有一个看起来像CRTP但更疯狂的解决方法:
#include <iostream>
template <class SecondType>
struct FirstBase
{
SecondType* _ptr;
};
template <class FirstType>
struct SecondBase
{
FirstType* _ptr;
};
struct FirstDerived
: public FirstBase<SecondBase<FirstDerived>>
{
};
struct SecondDerived
: public SecondBase<FirstBase<SecondDerived>>
{
};
int main()
{
FirstBase<SecondDerived> x;
SecondBase<FirstDerived> y;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果有人有更优雅的方法来做到这一点,我会很高兴看到它。