开发者

What's the proper way to share an enum across multiple files?

I would like to use the same enum in both the client and server parts of my current (C++) project, but am unsure of the proper way 开发者_StackOverflow中文版to do this. I could easily just write the enum in it's own file and include that in both files, but that feels like it's poor practice. Would putting it in a namespace and then including it in both be the right way to do it?

I know this is a bit subjective, if there's a better place for "best practice" questions please direct me to it.

Edit (elaboration): I'm sending data from the client to the server and in this case I'd like tell the client about changes in state. However, I'd like to avoid sending all of the information that makes up a state every time I'd like to change it, instead I want to just send a number that refers to an index in an array. So, I figure the best way to do this would be with an enum, but I need the same enum to be on both the client and server so that they both understand the number. Hope that makes sense.


Putting it in a header file seems reasonable, and wrapping it in a namespace can be useful too. Something i find myself doing with enums is

contents of whatevsenum.hpp:

namespace whatevs
{
    enum Enum
    {
        FOO = 0,
        BAR,
        BLARGH,
        MEH,
        SIZE
    };
} // namespace whatevs

and then whenever i need to use it in a header/source file elsewhere:

#include "whatevsenum.hpp"

void do_something_with(whatevs::Enum value)
{
    // do stuff
}

...

do_something_with(whatevs::FOO);


tl;dr: Put it in a header file (*.h) and #include the header file wherever you need to use the enum.

note: this applies to the new (C++11) enum classes as well.

Using a namespace isn't necessary. Including a header file (NOT a .cpp file) in multiple places is common and necessary in most cases. Header files should only include function/method declarations and type definitions as a general rule (this includes class definitions, struct definitions, and yes, enum definitions). Template functions and methods also need to be defined (not just declared) in a header file.

The other thing to remember about header files is that you should always use an include guard to avoid multiple definitions.

This FAQ may help, but probably will not be sufficient if you need a more complete introduction to C++

Declarations:

void foo(int bar); //Goes in a header file

class argle;

Definitions:

// Put this in a .cpp file
int foo(int bar) {
    return bar - 42;
};

// Put this in a header file
template<type T>
int baz(T t) {
    return 42;
}

// Put this in a header file
struct bargle {
    int fizz;
    char *whizz;
}

EDIT:

Found this, it should help you with understanding what to put in which file(s). In fact, this whole wikibook looks like a good resource for a C++ learner: http://en.wikibooks.org/wiki/C%2B%2B_Programming

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜