ぼく用あれこれまとめ
typedef テンプレート
最終更新:
bokuyo
-
view
typedefテンプレート
template<typename T> typedef std::vector<T> vec<T>; //もしくは //typedef std::vector<T> vec;
- 上に示した「typedefテンプレート」はC++の規格では実装されていません。
- C++の言語設計者が導入しようか検討しているそうです。
実装されていないけれど使いたい
- マクロで実装
- 継承で実装
- クラステンプレートのメンバによる実装
クラステンプレートのboost::shared_ptrをtypedefするには?
#include <boost\shared_ptr.hpp> class EventMsg { public: int param; }; typename boost::shared_ptr<EventMsg> EventMsgPtr;
- shared_ptrを意識しないでいいように、typedefで包んでみた。
- 汎用性を高めようと、int型からT型へと、EventMsgをクラステンプレートにしてみたら次のようになった。
template <typename T> class EventMsg { public: T param; }; template <typename T> typedef boost::shared_ptr<EventMsg<T>> EventMsgPtr<T>;
- しかし、typedefテンプレートは規格外なので、使えない。
- さてどうしよう?
解決法: クラステンプレートのメンバによる実装
#include <iostream> #include <boost\shared_ptr.hpp> template <typename T> class EventMsg { public: int param; }; template <typename T> class EventMsgPtr { public: typedef boost::shared_ptr< EventMsg<T> > Type; }; int main() { EventMsgPtr<int>::Type msg = EventMsgPtr<int>::Type(new EventMsg<int>); msg->param = 156; std::cout << msg->param << std::endl; return 0; }
- もしくはこう↓
template <typename T> class EventMsg { public: int param; typedef boost::shared_ptr< EventMsg<T> > Ptr; };
- newするの忘れてて、assert出まくりでびびった…。
参考文献
- MSDN - typedef テンプレート
- C++ テンプレート完全ガイド (Programmer's SELECTION): David Vandevoorde, Nicolai M. Josuttis, 津田 義史
- p.p. 208~209
- MSDN - C/C++ 用語集
- この記事とは関係ないけれど、面白い記事がたくさん載ってたので。