2013-06-03 47 views
3

考虑以下设计:相互依存的类模板设计?

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

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

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

如何解决这个问题?

+0

这个模拟到底是什么? – chris

+0

为什么上面的课堂设计?你想要解决什么现实生活中的问题? – Andrzej

回答

1

也许一个变通的东西,看起来像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; 
} 

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

+0

我会假设你不希望我们更改模板太多,因为要做到这一点,没有模板会很容易 – aaronman

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一起cos无所谓。 T会被你传递的任何东西所取代,当模板在编译之前被专门化时会发生这种情况。

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