共用方式為


別名

您可以使用 別名宣告 命名為當做先前宣告型別的同義字。(這個機制非正式也稱為 型別別名)。 您也可以使用這個機制建立 別名範本,特別用來自訂配置器。

using identifier = type;

備註

  • identifier
    別名的名稱。

  • type
    這個型別識別項建立別名。

別名不會引入新的型別,而且無法變更現有型別名稱的意義。

別名的簡單表單與 C++03 的 typedef 機制是相同的:

// C++11
using counter = long;

// C++03 equivalent:
// typedef long counter;

這兩個啟用型別「計數器」的變數的建立。 更有用的項目與這個型別的名稱為 std::ios_base::fmtflags的:

// C++11
using fmtfl = std::ios_base::fmtflags;
// C++03 equivalent:
// typedef std::ios_base::fmtflags fmtfl;

fmtfl fl_orig = std::cout.flags();
fmtfl fl_hex = (fl_orig & ~std::cout.basefield) | std::cout.showbase | std::cout.hex;
// ...
std::cout.flags(fl_hex);

別名的 typedef 的對等用法與函式指標一起使用,不過容易讀取的多:

// C++11
using func = void(*)(int);

// C++03 equivalent:
// typedef void (*func)(int);

// func can be assigned to a function pointer value
void actual_function(int arg) { /* some code */ }
func fptr = &actual_function;

typedef 機制的限制是它不使用樣板。 不過,這個型別在 C++11 的別名語法啟用別名範本的建立:

template<typename T> using ptr = T*; 

// the name 'ptr<T>' is now an alias for pointer to T
ptr<int> ptr_int;

範例

下列範例示範如何使用具有自訂的別名範本配置器在這個案例中,整數向量型別。 您可以用 int 取代任何型別建立方便別名隱藏複雜參數清單中的主要功能程式碼。 您可以在您的程式碼中的自訂配置器可能改善可讀性和減少引入錯誤的字造成的 Bug 的風險。

#include <stdlib.h>
#include <new>

template <typename T> struct MyAlloc {
    typedef T value_type;

    MyAlloc() { }
    template <typename U> MyAlloc(const MyAlloc<U>&) { }

    bool operator==(const MyAlloc&) const { return true; }
    bool operator!=(const MyAlloc&) const { return false; }

    T * allocate(const size_t n) const {
        if (n == 0) {
            return nullptr;
        }

        if (n > static_cast<size_t>(-1) / sizeof(T)) {
            throw std::bad_array_new_length();
        }

        void * const pv = malloc(n * sizeof(T));

        if (!pv) {
            throw std::bad_alloc();
        }

        return static_cast<T *>(pv);
    }

    void deallocate(T * const p, size_t) const {
        free(p);
    }
};

#include <vector>
using MyIntVector = std::vector<int, MyAlloc<int>>;

#include <iostream>

int main () 
{
    MyIntVector foov = { 1701, 1764, 1664 };

    for (auto a: foov) std::cout << a << " ";
    std::cout << "\n";

    return 0;
}

Output

  

請參閱

參考

using 關鍵字