Skip to content

Last updated:2026-10-12

C++ using Declarations and Aliases

About the Author:

Personal WeChat official account:

wechat

Basic Usage

Local and global using; see the cases below for the concrete operations and usage:

#include <iostream>
#define isNs1 1
//#define isGlobal 2
using namespace std;
void func() 
{
    cout<<"::func"<<endl;
}

namespace ns1 {
    void func()
    {
        cout<<"ns1::func"<<endl; 
    }
}

namespace ns2 {
#ifdef isNs1 
    using ns1::func;    /// ns1中的函数
#elif isGlobal
    using ::func; /// 全局中的函数
#else
    void func() 
    {
        cout<<"other::func"<<endl; 
    }
#endif
}

int main() 
{
    /**
     * 这就是为什么在c++中使用了cmath而不是math.h头文件
     */
    ns2::func(); // 会根据当前环境定义宏的不同来调用不同命名空间下的func()函数
    return 0;
}
For the complete code see: using_global.cpp

Changing Accessibility

class Base{
public:
 std::size_t size() const { return n;  }
protected:
 std::size_t n;
};
class Derived : private Base {
public:
 using Base::size;
protected:
 using Base::n;
};

Class Derived privately inherits Base, so for it the member variable n and the member function size are private. By using using declarations, their accessibility can be changed: in the example above, size can be accessed with public permission and n with protected permission. For the complete code see: derived_base.cpp

Function Overloading

During inheritance, a derived class can override zero or more instances of an overloaded function; as soon as one overloaded version is defined, all the other overloaded versions become invisible.

If, for a set of overloaded functions in a base class, we need to change one of them in the derived class and keep the others visible, we would have to redefine every version, which is extremely tedious.

#include <iostream>
using namespace std;

class Base{
    public:
        void f(){ cout<<"f()"<<endl;
        }
        void f(int n){
            cout<<"Base::f(int)"<<endl;
        }
};

class Derived : private Base {
    public:
        using Base::f;
        void f(int n){
            cout<<"Derived::f(int)"<<endl;
        }
};

int main()
{
    Base b;
    Derived d;
    d.f();
    d.f(1);
    return 0;
}
In the code above, a using declaration in the derived class names a function without specifying a parameter list, so a single using declaration for a base-class member function adds all of its overloaded instances to the derived class's scope. At this point, the derived class only needs to define the functions specific to it, without redefining the other functions it inherits.

For the complete code see: using_derived.cpp

Replacing typedef

In C, the syntax typedef A B is common: it defines B as type A, that is, it gives type A the alias B.

Corresponding to typedef A B, using B=A performs the same operation.

typedef vector<int> V1; 
using V2 = vector<int>;
For the complete code see: using_typedef.cpp

Comments