エイリアス

エイリアスの宣言を使用して、以前に宣言した型のシノニムとして使用する名前を宣言できます (このメカニズムは非公式には型エイリアスとも呼ばれます)。 また、このメカニズムを使用してエイリアス テンプレートを作成できます。このテンプレートはカスタム アロケーターに特に便利にな場合があります。

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 を任意の型に置き換えて、便利なエイリアスを作成することで、主要な機能コード内の複雑なパラメーター リストを隠ぺいできます。 コード全体でカスタム アロケーターを使用することで読みやすくして、入力ミスによるバグが発生するリスクを減らすことができます。

#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;
}

出力

  

参照

関連項目

using キーワード