开发者

Namespace for a single method c++

Let's say i have a header file Snake.h:

#include "SnakeBodyPart.h"
#include "GUI.h"
//...

And SnakeBodyPart.h is (among other things) :

#include "GUI.h"
class SnakeBodyPart {
    private :
        GUI::Orientation orientation;
}

And at last GUI.h :

class GUI {
    enum Orientation { NORTH, EAST, SOUTH, WEST };
}

Now in Snake.cpp i want to do the following:

void Snake::turn(){
    if(bodyPart.getOrientation() == GUI::EAST){
        //do something
    else if (bodyPart.getOrientation() == GUI::SOUTH){
        //do something
    else if ...
}

I think you get the point. What i would like to know is: is it possible to set a namespace for a single method? Like giving the namespace GUI to Snake::turn, so i can just type bodyPart.getOrientation() == EA开发者_开发百科ST ?

I'm having a few enums with different namespaces in Snake.cpp and would like to make the code more readible, by giving certain methods certain namespaces, not just one namespace for Snake.cpp. Is this possible?


Please note that in your example, GUI is not a namespace but a class.

That being said, inside turn() you can write using namespace GUI; to access all identifiers in the GUI namespace without explicitely qualifying them. Alternatively, you can import single symbols using e.g. using GUI::EAST;, too:

void Snake::turn(){
    using namespace GUI;
    if(bodyPart.getOrientation() == EAST){
        //do something
    else if (bodyPart.getOrientation() == SOUTH){
        //do something
    else if ...
}


Since GUI is a class, just be clear and explicit and type out GUI:: so everyone reading the code knows the context of what's happening. You have to write the code just once with a little extra typing, but people may have to read the code for years.

EDIT: Alternately if GUI doesn't need to be a class (enums only), change it to a namespace and do using namespace GUI; in your function.


If what you want is simply short human readable code and not actual resolution created by a namespace you can use a typedef or macro to achieve the desired results.

Alternately you do not need to contain your enum within a class or namespace unless you are worried about naming conflicts in which case including the header would be enough to be able to create an Orientation variable or reference the directional members of the enum directly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜