tags:

views:

110

answers:

2

I'm trying to question my own code correctness on the following minimalist example in which a header file lifts a identifier into the current namespace.

#include <string>

namespace mine {

    using std::string; // std::string lifted into mine

    struct agent
    {
        string name;
    };
}

This is a suggestion I made recently as another alternative to the use of a typedef:

#include <string>

struct agent
{
    private:
        typedef std::string string;
    public:
        string name;
};

I considered the first option more correct since it makes use of my own namespace and this is a practice that one should get used to (that of namespace creation and management). Meanhile, since the identifier is being lifted inside a namespace I control, it makes this a safe approach.

However, I'm having second thoughts. For one, careless use of the namespace mine, with a using directive for instance, will also bring std::string into view. Another problem is I'm exposing std::string too much. Perhaps even to areas of the namespace mine where it isn't necessary or desirable.

It's seems to me more correct to always work at the lowest possible scope and work up from there. Expose only the absolutely necessary. The fact I make the typedef private on the second example was exactly because of this. But then I don't follow my own advise with the second example.

But on the other hand, my concerns result from the fact someone might misuse the namespace mine:

using namespace mine;

At first glance, we know this is not a correct usage pattern for a namespace. But it can't be denied there are instances when it may be desirable. How valid do you think is the first approach?

+8  A: 

I would have thought the obvious solution is:

namespace mine { 
    struct agent
    {
        std::string name;
    };
}

I personally do not use using directives in header files at all. In implementation files, certainly.

anon
Absolutely! In any case the example serves those cases where he author has too many types to be declared inside a class and wishes to simplify their typing. I felt I gave the wrong advise with the first example. But would like some thoughts, since std::string is rather innocuos.
Krugar
I guess I'm not clear what you are really asking about. But I would observe that in C++ namespaces are not design tools, so if you are having a lot of namespace issues, you probably have too many namespaces.
anon
+7  A: 

I normally do this:

// In header file:

#include <string>

namespace mine {

    struct agent
    {
        std::string name;
    };
}

// In source file:

using std::string; 

namespace mine {
   // Code
}

That way you don't have to write out std:: over and over again in the implementation, but you avoid the problem of people who use your headers inadvertently importing std:: symbols.

Tyler McHenry