c++ - 相互依赖的类模板设计?

标签 c++ class templates c++11

考虑以下设计:

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

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

哪里First type 有一个指向 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;
}

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

关于c++ - 相互依赖的类模板设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16889818/

相关文章:

C++类Classname的使用;

c++ - 将 &变量传递给函数意味着什么?例如, string& insert ( size_t pos1, const string& str );

c++ - 如何让QRadioButton正确显示焦点边框

php - 如何使用 native joomla 2.5 php 对象显示 Joomla 数据库表

c++ 与成员变量同名的内联友元函数

c++ - 如何在 C++ 中实现 "virtual template function"

c++ - 如何在c++中包含头文件?

javascript - python 瓶 : Assigning a python variable to Javascript variable

c++ - 为什么模块仍然可以访问在外部模块外部实现的方法

python - 如何在 boost::python 扩展模块中正确组合 C++ 和 Python 代码?