[英]Workarounds for the forward-declared class enumeration problem?
I am maintaining a large code base and am using a combination of forward declarations and the pImpl idiom to keep compile times down and reduce dependencies (and it works really well,) 我正在维护一个庞大的代码库,并使用前向声明和pImpl习惯用法的组合来减少编译时间并减少依赖性(并且它工作得很好)
The problem I have is with classes that contain public enumerations. 我遇到的问题是包含公共枚举的类。 These enumerations cannot be forward declared so I am left with no option but to include the class header.
这些枚举不能向前声明,所以我没有选择,只能包含类头。 For example:
例如:
// Foo.h
class Foo
{
public:
enum Type
{
TYPE_A,
TYPE_B,
};
...
};
// Bar.h
#include "Foo.h" // For Foo::Type
class Bar
{
public:
void someFunction(Foo::Type type);
...
};
So, I'm looking for ways to avoid this and can only think of the following: 所以,我正在寻找避免这种情况的方法,只能想到以下几点:
Move the class enumerations to a separate 'types' namespace 将类枚举移动到单独的“类型”命名空间
// FooTypes.h
namespace FooTypes
{
enum Type
{
TYPE_A,
TYPE_B,
};
}
// Bar.h
#include "FooTypes.h"
class Bar
{
public:
void someFunction(FooTypes::Type type);
...
};
Use int instead of the enumeration 使用int而不是枚举
// Bar.h
class Bar
{
public:
void someFunction(int type);
...
};
What have I missed? 我错过了什么? How do other people get around this limitation (not being able to forward declare enumerations.)
其他人如何解决这个限制(无法转发声明枚举。)
将枚举放在包含PIMPL的类中。
Put the enumeration into its own type: 将枚举放入自己的类型:
struct FooEnum
{
enum Type
{
TYPE_A,
TYPE_B,
};
};
Then Foo
and Bar
can both access FooEnum::Type
and Bar.h
doesn't need to include Foo.h
. 然后
Foo
和Bar
都可以访问FooEnum::Type
而Bar.h
不需要包含Foo.h
I'd argue that enums are a bad idea to start with, but in general for constants/the many things like constants in C++ none of which are quite constants and all of which have issues. 我认为枚举是一个坏主意,但通常对于常量/很多东西,比如C ++中的常量,其中没有一个是常量,所有这些都有问题。 I like to put it into a struct then have the classes using it inherit from the struct.
我喜欢将它放入一个结构中然后使用它从继承结构的类。
I'd also argue that the pimpl idiom is bad. 我也认为pimpl成语很糟糕。 Actually I am sure it's a poor way to do things.
实际上我确信这是一种糟糕的做事方式。 It's something that works but is awkward and a bit silly.
这是有效的,但很尴尬,有点傻。 It's also easy to avoid, and the only reason it comes about is due to people using yet other bad design choices.
它也很容易避免,它出现的唯一原因是人们使用其他糟糕的设计选择。
Usually someone just tacks on OOP stuff to a class they designed to be concrete. 通常有人会把OOP的东西放到他们设计的混凝土上。 Then you get the mixed inheritance case and the plethora of issues it causes such as super slow compile time.
然后你得到混合继承的情况和它引起的过多问题,比如超慢的编译时间。 Instead, consider pure virtual base classes, then writing your libs to that to avoid templates and avoid the forward declaration problem.
相反,请考虑纯虚拟基类,然后将lib写入其中以避免模板并避免前向声明问题。 Not for everything, but definitely for the cases where you are generating code for lots of classes.
不是一切,但绝对适用于为许多类生成代码的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.