Can the keyword using in C++ be used with something except of keyword namespace? If no -- so why can't we simply write "namespace ..."? If yes -- may you give some examples of its usage in "non-namespace" context, please?
Thanks.
Can the keyword using in C++ be used with something except of keyword namespace? If no -- so why can't we simply write "namespace ..."? If yes -- may you give some examples of its usage in "non-namespace" context, please?
Thanks.
There are multiple different uses for the keyword using
:
using namespace std
.using std::vector
.using B::f;
where B
is a base class and f
is a possibly overloaded member of this base class.using B::B;
.template <typename T> using singleton = std::pair<int, T>;
.Yes, you can using
a single name. For instance
using std::swap;
does a "using" only to swap
from namespace std
, while
using namespace std;
pulls in every name in std.
Yes. Its used to declare namespace members. For example:
namespace homebrew
{
template<typename T>
struct vector {};
}
int main()
{
{
using namespace std;
vector<T> v; //Refers to std::vector
}
{
using homebrew::vector;
vector<T> v; //Refers to homebrew::vector
}
}
Also is used to do the same with class members:
#include <iostream>
struct B {
virtual void f(int) { std::cout << "B::f\n"; }
void g(char) { std::cout << "B::g\n"; }
void h(int) { std::cout << "B::h\n"; }
protected:
int m; // B::m is protected
typedef int value_type;
};
struct D : B {
using B::m; // D::m is public
using B::value_type; // D::value_type is public
using B::f;
void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides B::f(int)
using B::g;
void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible
// as members of D
using B::h;
void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int)
};
Finally, its used since C++11 to define type aliases, template aliases included:
using vector_of_bool = std::vector<bool>;
template<typename T>
using vector_t = std::vector<T>;
The examples were extracted from the cppreference.com documentation about using
keyword.