LoginSignup
219
187

More than 5 years have passed since last update.

typedef は C++11 ではオワコン

Last updated at Posted at 2014-12-21

昨日 typedef について大阪 C++ 勉強会でちょっと話題が出ていて,そういえば typedef がどうしてダメで型エイリアスだと良いのかみたいな話あまりまとまってない気がしたのでメモ.

typedef はこんな感じの構文でした.

typedef {oldtype} {newtype};

これは C++11 では using 型エイリアスを使って書けます.

using {newtype} = {oldtype};

この時点だとどっちでも良い感じがしますが,例えば関数ポインタなんかは using のほうが見やすいです.

typedef void (*f)(int, char);
using f = void (*)(int, char);

また,using のほうはテンプレート化することができます.

template<class Value>
using dict = std::map<std::string, Value>;

これは typedef に対して非常に大きな利点です.

例えば,自分用のアロケータを使った std::vector を使いたいとします.
using エイリアスを使うとこんな感じに書けます.

template<class T>
struct greate_allocator;

template<class T>
using greate_vector = std::vector<T, greate_allocator<T>>;

template<class T>
struct greate_stack {
    greate_vector<T> buffer;  // 使ってみる
};

これを C++03 まででやろうとすると若干面倒でした.

template<class T>
struct greate_allocator;

template<class T>
struct greate_vector {
    typedef std::vector<T, greate_allocator<T>> type;
};

template<class T>
struct greate_stack {
    typename greate_vector<T>::type buffer; // 使ってみる
}

メンバ型を使っていますが,::type をつけないといけないことや,場合によって typename を付けないといけないのが面倒ですね.typename を付けないといけないのは,::type が本当に型を表すメンバなのかがこの時点では分からない(T 次第)ためです.

結論

型エイリアス使おう.

219
187
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
219
187