gpt4 book ai didi

c++ - 具有继承模板类的循环依赖

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:09 25 4
gpt4 key购买 nike

我遇到了循环依赖问题。基本上我有两个类,第一个是模板类,它使用第二个类的一些功能。第二个类继承 self 的模板类。

下面是一个简化的结构:

// Foo.h
#pragma once
#include "Bar.h"

template <class T> class Foo
{
public:
void DoSomething();
};

template <class T> void Foo<T>::DoSomething()
{
Bar::GetInstance()->LogEvent();
}


//Bar.h
#pragma once
#include "Foo.h"

class Bar : public Foo<Bar>
{
public:
static Bar* GetInstance();
void LogEvent();
};


//Bar.cpp
#include "Bar.h"

Bar* Bar::GetInstance()
{
// return instance of Bar singleton class
}

void Bar::LogEvent()
{
// log some event in a file
}

现在的问题是,当我编译代码时,我在 bar.h 中收到以下错误

Bar.h() : error C2504: 'Foo' : base class undefined
Bar.h() : error C2143: syntax error : missing ',' before '<'

据我所知,这绝对是一个依赖性问题。如果我从“DoSomething”中删除对“LogEvent”的调用,并从 Foo.h 中删除引用“Bar.h”,问题就会消失。

然而,这并不是真正的解决方案,因为 Foo 需要 Bar 包含的功能,相反,bar 继承自 Foo,需要包含对 Foo.h 的引用。

那么 - 我该如何解决这个问题?我已经查看了有关循环引用的其他帖子,但我无法解决问题。

谢谢

最佳答案

根据您发布的代码,foo.h 不需要包含 bar.h,如果不包含,问题就会消失。

重要的是编译器在看到 Bar 之前先看到 Foo,如果 #include "bar.h" 位于 foo.h 的顶部(取决于顺序),这可能不会发生foo.h 和 bar.h 在消费模块中被#include

也就是说,如果一个基类需要假设一个特定的派生类并按名称调用它,这似乎可能存在设计问题(基类中的虚函数可以工作吗?)。但如果不了解全貌,我无法做出判断。

根据下面的评论,我认为您可以通过添加第三个文件来解决眼前的问题:

// LogEvent.h

void LogEvent(...);

// LogEvent.cpp
#include "bar.h"

void LogEvent(...)
{
Bar::GetInstance()->LogEvent(...);
}

然后修改foo.h如下:

// Foo.h
#pragma once
#include "LogEvent.h"

template <class T> class Foo
{
public:
void DoSomething();
};

template <class T> void Foo<T>::DoSomething()
{
LogEvent(...);
}

除非还有其他问题,否则至少应该让您进行编译。

关于c++ - 具有继承模板类的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com