using is a keyword to specify the a namespace(s) used or the namespace(s) of the data types used.
Example: using to specify the namespace(s) of the data types used
#include <iostream>
#include <string>
int main()
{
using std::cout;
using std::string;
const string s = "Hello world";
cout << s;
}
Example: using to specify the namespace(s) used
#include <iostream>
#include <string>
int main()
{
using namespace std;
const string s = "Hello world";
cout << s;
}
- Use using-directives for transition, for foundational libraries (such as std), or within a local scope [1]
- Don't put a using-directive in a header file [2,3,8]
- Don't write a using-directive before an #include [3]
- Prefer using over typedef for defining aliases [4, 7]
- Do not qualify namespaces of function templates for which user-defined overloads might exist. Make the name visible by using using instead and call the function unqualified [6]. For example, do not call
std::swapif the objects to-be-swapped are nonstandard. Useusing std::swapinstead, then callswap. The compiler will use the nonstandard swap if it exists
- [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 14.5. Advice. page 417: '[10] Use using-directives for transition, for foundational libraries (such as std), or within a local scope'
- [2] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 14.5. Advice. page 417: '[11] Don't put a using-directive in a header file'
- [3] Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 59: 'Don't write namespace usings in a header file or before an #include'
- [4] C++ Core Guidelines item T.43: 'Prefer using over typedef for defining aliases'
- [5] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 2.7.3: 'Implement binary operators as free functions'
- [6] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 3.2.3: 'Do not qualify namespaces of function templates for which user-defined overloads might exist. Make the name visible instead and call the function unqualified'
- [7] Gottschling, Peter. Discovering Modern C++: An Intensive Course for Scientists, Engineers, and Programmers. Addison-Wesley Professional, 2015. Chapter 3.4.4: 'Prefer using instead of typedef'
- [8] Jason Turner, cppbestpractices: Never Use
using namespacein a Header File