5

考虑以下设计:

template <class SecondType>
struct First
{
    SecondType* _ptr;
};

template <class FirstType>
struct Second
{
    FirstType* _ptr;
};

其中First类型具有指向类型的指针,Second反之亦然。问题是我不能声明它,因为它们是相互依赖的,我应该声明First<Second<First<Second...>>>.

如何解决这个问题呢 ?

4

3 回答 3

2

也许是一种看起来像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;
}

如果有人有更优雅的方式来做到这一点,我会很高兴看到它。

于 2013-06-03T04:59:29.227 回答
0

不确定您要达到的目标,但以下编译良好。

template <class T> struct First  { T* _ptr; };
template <class T> struct Second { T* _ptr; };

int main(){
   First<Second<First<Second<void>>>> a; // or
   First<Second<First<Second<nullptr_t>>>> b;
   return 0;
}

注意我完全替换了 FirstType,SecondType 因为没关系。T 将被您传递的任何内容替换,这将在模板在编译之前被专门化时发生。

于 2013-06-03T05:00:07.213 回答
0

这是另一个可能更优雅的解决方案,它根本不需要 void。我不知道你是否可以接受继承,但我认为它运作良好。

#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
struct Base {
    //make all functions virtual
};
template <class SecondType>
struct First: public Base
{
    SecondType* _ptr;
    First(SecondType * st) {
        _ptr = st;
    }
    First() {
    }
};

template <class FirstType>
struct Second: public Base
{
    FirstType* _ptr;
    Second(FirstType * ft) {
        _ptr = ft;
    }
    Second() {
    }
};

int main() {
    First<Base> f;
    Second<Base>  s;
    f._ptr = &s;
    s._ptr = &f;
    cout << s._ptr << endl;
}
于 2013-06-03T15:05:41.213 回答