8

Is there a possibility to have a using directive whose scope is limited to a single class?

Note, that what I want to "use" is not contained in the parent of the current class.

For simplicity, assume the following exmple:

#include<vector>

class foo
{
using std::vector; //Error, a class-qualified name is required
}

Another interesting thing to know is, if the using directives are included, if a header is included:

MyClassFoo.h:
#include<vector>

using std::vector; //OK
class foo
{

}

And in

NewHeader.h
#include "MyClassFoo.h"
...

how can I prevent "using std::vector" to be visible here?

S.H
  • 875
  • 2
  • 11
  • 27
  • Is there a possibility to create a templated type alias for "std::vector" that is then called "vector"? That way it'd do the same as what I want the using std::vector to do inside the class – S.H Dec 05 '14 at 09:50
  • Yes, `using` declarations can be templated when creating type aliases, and it's okay to call that type alias `vector` since it's in another scope from `std::vector`. – Some programmer dude Dec 05 '14 at 09:53
  • 1
    I think it's worth pointing out that this isn't a *using directive*, it's a *using declaration*. Using directives introduce **namespaces**. –  Dec 05 '14 at 09:54
  • thanks, and I changed the "directive" to "declaration" – S.H Dec 05 '14 at 12:15
  • Close to what you want using a [wrapper namespace](http://stackoverflow.com/a/4363431/86967). – Brent Bradburn May 02 '15 at 14:15

2 Answers2

4

Since you tagged c++11:

#include<vector>

class foo
{
  template<typename T>
  using vector = std::vector<T>;
};
Drax
  • 12,682
  • 7
  • 45
  • 85
  • 3
    Also, `template using vector = std::vector;` if you ever have *any* inclination of using the optional allocator. – WhozCraig Dec 05 '14 at 10:03
  • This looks, good, but unfortunately it gives me "unrecognizable template declaration/definition"?! – S.H Dec 05 '14 at 12:18
  • @S.H You need to compile with -std=c++11 with a recent enough compiler – Drax Dec 05 '14 at 16:08
  • Since I'm compiling with C++11, it's a problem of VS2012 -> [link](http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx) to supported VS C++11 features – S.H Dec 10 '14 at 11:07
  • @S.H Yep seems it was introduced in VS2013: http://msdn.microsoft.com/en-us/library/vstudio/dn467695.aspx, sad =/ – Drax Dec 10 '14 at 13:00
0

As for your first requirement, you can use a namespace so that the scope of using namespace is limited to a single class.

#include<vector>

namespace FooClasses
{
    using namespace std; //The scope of this statement will NOT go outside this namespace.

    class foo
    {
      vector<int> vecIntVector; 
    };

}// namespace FooClasses

For your second case, do make use of #define and #undef wisely.

MNS
  • 1,354
  • 15
  • 26