2

Possible Duplicate:
Scoped using-directive within a struct/class declaration?
Why “using namespace X;” is not allowed inside class/struct level?

I would like to introduce only std::string into structure. Why is the below considered illegal?

#include <iostream>
#include <string>

struct Father
{
    using std::string;

    string sons[20];
    string daughters[20];
};

But oddly enough, i can do the following the in a function

int main()
{
    using std::string;
}

Update: C++ uses the same keyword with different semantics.

c++ uses the keyword "using" to introduce a data member or function from the base class into the current class. Thus when i wrote using std::string inside a struct declaration, compiler is assuming that i am trying to introduce a member from a base class std. But std is not a base class, rather it is a namespace. Thus

struct A
{
     int i;
}

struct B:A
{
     using A::i; // legal
     using std::string// illegal, because ::std is not a class
}

the same "using" keyword is also used to access a member of a particular namespace.

So, i am guessing compiler decides the semantics of "using" based on where it is declared.

Community
  • 1
  • 1
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 2
    Please **do not** remove the automatically inserted "possible duplicate" link when you edit the question. I understand that you updated in order to explain why you think it's *not* a duplicate of the suggested question, and that's perfectly acceptable/encouraged behavior. But you should either let your edits bump up the question and attract re-open votes from users who notice it in the list, or use the "flag" link to ask a moderator to examine and re-open it as per your updates. Removing the automatically inserted link is very strongly discouraged; the system will remove it upon reopening. – Cody Gray - on strike Mar 25 '12 at 08:01
  • (If removing it was an accident in this case—i.e., your edits collided in time—then I apologize for the harsh-sounding tone. Just take it as good advice for the future! :-)) – Cody Gray - on strike Mar 25 '12 at 08:02

2 Answers2

2

I don't know the answer to your actual question, but you can use a typedef:

struct Father
{
    typedef std::string string;

    string sons[20];
    string daughters[20];
};
mkj
  • 2,761
  • 5
  • 24
  • 28
0

It's just not allowed by the language unfortunately, but there's a workaround:

namespace Father_Local
{
    using std::string;

    struct Father
    {
        //...
    };
}

using Father_Local::Father;

The advantage of this approach is that you could in principle write a using directive e.g.

using namespace boost::multi_index;

there and save yourself a load of typing and clutter in a header file. None of this affects the rest of the code - Father gets imported into its proper namespace by the using at the end and everything works fine.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80