using
keyword
The using
keyword is used to alias names. It was introduced in C++11.
using namespace std;
Use the using keyword to alias a longer type name, for example with Google Test:
using T = Testing::T;
You can also do something like this (from gxf code)
template <typename T>
using Expected = Expected<T, gxf_result_t>;
using ll = long long;
- There is also typedef which does the same thing (
typedef long long ll
;)
Visibility
Visibility of using
inside a class in same as accessing member variables. That’s why a lot of std things like std::is_same and std::conditional are implemented with a struct to have default public visibility.
struct ExampleStruct {
using MyType = int; // Public by default
};
class ExampleClass {
using MyType = int; // Private by default
};
If you try to use it afterwards,
ExampleStruct::MyType a = 5; // ✅ Works (public)
ExampleClass::MyType b = 5; ❌ Error (private)
Typedef vs. Using
typedef vs. using??
Seems like they both do the same thing, but you can leverage using for templates.
See https://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using.
Example
template <typename T>
typedef std::vector<T> Vec; // ❌ Error!
template <typename T>
using Vec = std::vector<T>; // ✅ Works perfectly
// Afterwards...
Vec<int> v;
You had to use a workaround before
template <typename T>
struct Vec {
typedef std::vector<T> type;
};