在C ++中,当我需要使用枚举时,如何避免#include头文件? [英] In C++, how can I avoid #including a header file when I need to use an enumeration?

查看:710
本文介绍了在C ++中,当我需要使用枚举时,如何避免#include头文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++头文件中,我尝试使用向前声明(类MyClass;),而不是#include类头,正如许多C ++编码标准中推荐的那样(Google C ++ Style Guide是一个)。

In my C++ header files I try to use forward declarations (class MyClass;) instead of #including the class header, as recommended in many C++ coding standards (the Google C++ Style Guide is one).

不幸的是,当我介绍枚举时,我不能再做向前声明。像这样:

Unfortunately, when I introduce enumerations, I can't do the forward declaration any more. Like this:

//// myclass1.hpp ////

class MyClass1
{
    enum MyEnum1
    {
        Enum_A, Enum_B, Enum_C
    };
};

//// myclass2.hpp ////

// I want to avoid this
#include "myclass1.hpp"

// I'd prefer to do this (forward declaration)
class MyClass1;

class MyClass2
{
    // This is o.k.: I only need to forward declare MyClass1
    MyClass1* ptr;

    // This forces me to #include, but I don't want to!
    void func( MyClass1::MyEnum1 e );
};

到目前为止我能想到的最好的解决方案是用成员常量替换枚举:

The best solution I can think of so far is to replace enums with member constants:

//// myclass1.hpp  ////

MyClass1
{
    static const int Enum_A;
    static const int Enum_B;
    static const int Enum_C;
};

//// myclass1.cpp ////

const int Enum_A = 1;
const int Enum_B = 2;
const int Enum_C = 3;

在这种情况下,解决方案似乎比问题更糟。

In this case, though, the solution seems worse than the problem.

我目前正在通过大规模C ++软件设计(Lakos)和使用传统代码(Feathers)查看依赖打破技术,但是我还没有找到一个好的解决方案。

I'm currently looking through Large Scale C++ Software Design (Lakos) and Working Effectively with Legacy Code (Feathers) for dependency breaking techniques, but I haven't found a good solution yet.

推荐答案

你不能转发declare枚举值 - 完成疯狂的道路。

You cannot forward declare enum values - and your workaround is a step down the path to complete madness.

您是否遇到由#include标头造成的任何重大编译速度下降?如果没有,只是#include他们。使用前进声明最佳做法是一个黑客。

Are you experiencing any major compilation slowdowns caused by #including headers? If not, just #include them. Use of forward declarations is not "best practice" it is a hack.

这篇关于在C ++中,当我需要使用枚举时,如何避免#include头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆