"Using" declaration with scope only on current class?
Asked Answered
S

2

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?

Sobersided answered 5/12, 2014 at 9:45 Comment(5)
Is there a possibility to create a templated type alias for "std::vector<T>" that is then called "vector"? That way it'd do the same as what I want the using std::vector to do inside the classSobersided
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.Admixture
I think it's worth pointing out that this isn't a using directive, it's a using declaration. Using directives introduce namespaces.Crinoline
thanks, and I changed the "directive" to "declaration"Sobersided
Close to what you want using a wrapper namespace.Clements
K
4

Since you tagged c++11:

#include<vector>

class foo
{
  template<typename T>
  using vector = std::vector<T>;
};
Kodok answered 5/12, 2014 at 10:1 Comment(5)
Also, template<class T, class... Args> using vector = std::vector<T, Args...>; if you ever have any inclination of using the optional allocator.Swatch
This looks, good, but unfortunately it gives me "unrecognizable template declaration/definition"?!Sobersided
@Sobersided You need to compile with -std=c++11 with a recent enough compilerKodok
Since I'm compiling with C++11, it's a problem of VS2012 -> link to supported VS C++11 featuresSobersided
@Sobersided Yep seems it was introduced in VS2013: msdn.microsoft.com/en-us/library/vstudio/dn467695.aspx, sad =/Kodok
I
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.

Insanity answered 5/12, 2014 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.