SlideShare a Scribd company logo
C++
テンプレートメタプログラミング

                           高橋晶(アキラ)

   ブログ:「Faith and Brave – C++で遊ぼう」
    http://d.hatena.ne.jp/faith_and_brave/
はじめに
Q.テンプレートメタプログラミングってなんぞ?

A.テンプレートのインスタンス化を利用して
  コンパイル時に評価されるプログラムを書こうぜ!
  っていうパラダイム
メタ関数
• コンパイル時に評価される関数
 template <class T> // Tがパラメータ
 struct identity {
    typedef T type; // typeが戻り値
 };

 identity<int>::type i; // int i;


テンプレートパラメータを関数のパラメータ、
入れ子型(nested-type)や
クラス内定数(static const T)を関数の戻り値を見なす。
特殊化で型特性の判別と条件分岐
テンプレートの特殊化を使って、
型がどんな特性を持ってるのかを判別する

以下はTがvoidかどうかを判別するメタ関数
 template <class T>
 struct is_void {        // void以外だったらfalseを返す
    static const bool value = false;
 };
 template <>
 struct is_void<void> { // voidだったらtrueを返す
    static const bool value = true;
 };
 bool a = is_void<int>::value; // bool a = false;
 bool b = is_void<void>::value; // bool b = true;
部分特殊化で型特性の判別
• 部分特殊化使った場合。
  パターンマッチみたいなもん。
 template <class T>
 struct is_pointer {      // ポインタ以外はfalseを返す
    static const bool value = false;
 };

 template <class T>
 struct is_pointer<T*> { // ポインタならtrueを返す
    static const bool value = true;
 };

 bool a = is_pointer<int>::value; // bool a = false;
 bool b = is_pointer<int*>::value; // bool b = true;
型を修飾する
• Tを受け取ってT*を返すメタ関数
 template <class T>
 struct add_pointer {
    typedef T* type;
 };

 add_pointer<int>::type p;
    // int* p;

 add_pointer<add_pointer<int>::type>::type pp;
    // int** pp;
再帰テンプレート
• メタ関数がメタ関数自身を呼ぶことによって
  再帰によるループを表現する
template <class T, int N>
struct add_pointer {
   typedef typename add_pointer<T*, N-1>::type type;
};

template <class T>
struct add_pointer<T, 0> { // 再帰の終了条件
   typedef T type;
};

add_pointer<int, 5> p; // int***** p;
応用例1 : コンパイル時if文(型の選択)
 テンプレートパラメータで条件式をbool値で受け取って
 パラメータがtrueの場合の型、falseの場合の型を選択する

 template <bool Cond, class Then, class Else>
 struct if_c;

 template <class Then, class Else>
 struct if_c<true, Then, Else> {
   typedef Then type;
 };

 template <class Then, class Else>
 struct if_c<false, Then, Else> {
   typedef Else type;
 };

 if_c<true, int, char>::type
 → int

 if_c<false, int, char>::type
 → char
応用例2 :
      コンテナ/配列からイテレータ/ポインタの型を取り出す
template <class Range>
struct range_iterator {        // 配列以外だったらRange::iterator型を返す
   typedef typename Range::iterator type;
};

template <class T, int N>
struct range_iterator<T[N]> { // 配列だったらT*型を返す
   typedef T* type;
};

template <class Range>
void foo(Range& r)
{
  typedef typename range_iterator<Range>::type Iterator;
}

vector<int> v;
int ar[3];

foo(v); // Iteratorの型はvector<int>::iteratorになる
foo(ar); // Iteratorの型はint*になる
応用例3:
        型のシグニチャから部分的に型を抜き出す
template <class Signature>
struct argument_of;

template <class R, class Arg>
struct argument_of<R(Arg)> { // 型がR(Arg)の形になってたら
   typedef R   result_type;   // 戻り値の型を取り出す
   typedef Arg argument_type; // 引数の型を取り出す
};

typedef argument_of<int(double)>::result_type   result;   // int
typedef argument_of<int(double)>::argument_type argument; // double



boost::result_ofで関数オブジェクトの戻り値の型を取得するときに使える
チューリング完全
特殊化によって条件分岐を表現し、
再帰テンプレートによってループを表現できる

これらのことから、C++テンプレートは
ほぼ(※)チューリング完全だと言われてるみたい。
つまり、コンパイル時に全てのアルゴリズムを解くことができる。

※再帰的に入れ子にされたテンプレートの
 インスタンス化は17回までは保証されてる。

『C++ Templates are Turing Complete』
http://ubiety.uwaterloo.ca/~tveldhui/papers/2003/turing.pdf

More Related Content

PPTX
Functions in c
PPT
Patrons de creation
PPTX
Arrays In C Language
PDF
Effective Modern C++ 勉強会#1 Item3,4
PDF
Hot C++: Rvalue References And Move Semantics
PDF
Constexpr 中3女子テクニック
PDF
12 分くらいで知るLuaVM
PDF
itft-Decision making and branching in java
Functions in c
Patrons de creation
Arrays In C Language
Effective Modern C++ 勉強会#1 Item3,4
Hot C++: Rvalue References And Move Semantics
Constexpr 中3女子テクニック
12 分くらいで知るLuaVM
itft-Decision making and branching in java

What's hot (20)

PPTX
Introduction à l’orienté objet en Python
PPT
Constructor
PDF
POO Java Chapitre 1 Classe & Objet
PPTX
Pointers in c++
DOCX
Tp1 compte rendu en langage c
PDF
中3女子が狂える本当に気持ちのいい constexpr
PDF
Pythonと型チェッカー
PDF
C++でできる!OS自作入門
PDF
C++ Template Meta Programming の紹介@社内勉強会
PPT
Runnable interface.34
PDF
Suphx: Mastering Mahjong with Deep Reinforcement Learning
PDF
Twitterのsnowflakeについて
PDF
templateとautoの型推論
PDF
Introduction à Python - Achraf Kacimi El Hassani
PPTX
Network miner 使ってみた
PDF
Django best practices for logging and signals
PDF
Ch 01 poo
PPTX
Introduction à JavaScript
PDF
ドメインオブジェクトの見つけ方・作り方・育て方
PDF
Ponteiros e Alocação Dinâmica
Introduction à l’orienté objet en Python
Constructor
POO Java Chapitre 1 Classe & Objet
Pointers in c++
Tp1 compte rendu en langage c
中3女子が狂える本当に気持ちのいい constexpr
Pythonと型チェッカー
C++でできる!OS自作入門
C++ Template Meta Programming の紹介@社内勉強会
Runnable interface.34
Suphx: Mastering Mahjong with Deep Reinforcement Learning
Twitterのsnowflakeについて
templateとautoの型推論
Introduction à Python - Achraf Kacimi El Hassani
Network miner 使ってみた
Django best practices for logging and signals
Ch 01 poo
Introduction à JavaScript
ドメインオブジェクトの見つけ方・作り方・育て方
Ponteiros e Alocação Dinâmica
Ad

Viewers also liked (20)

PDF
Template Meta Programming入門から応用まで
PDF
エクストリームC++11/14プログラミング
PDF
すごい constexpr たのしくレイトレ!
PDF
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
PDF
C++0x Variadic Type List
PDF
Boostのあるプログラミング生活
PDF
boost and c++11
PDF
中3女子でもわかる constexpr
PDF
C++1z draft
PDF
Lisp Meet Up #25, 8-bit PIC マイコン用ネイティブコンパイラの作成
PDF
What is template
PDF
Boost.SIMD
PDF
C++でCプリプロセッサを作ったり速くしたりしたお話
PDF
ゲーム開発者のための C++11/C++14
PDF
闇魔術を触ってみた
PDF
C++14 Overview
PDF
C++の黒魔術
PDF
プログラムの処方箋~健康なコードと病んだコード
PDF
C++の話(本当にあった怖い話)
Template Meta Programming入門から応用まで
エクストリームC++11/14プログラミング
すごい constexpr たのしくレイトレ!
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
C++0x Variadic Type List
Boostのあるプログラミング生活
boost and c++11
中3女子でもわかる constexpr
C++1z draft
Lisp Meet Up #25, 8-bit PIC マイコン用ネイティブコンパイラの作成
What is template
Boost.SIMD
C++でCプリプロセッサを作ったり速くしたりしたお話
ゲーム開発者のための C++11/C++14
闇魔術を触ってみた
C++14 Overview
C++の黒魔術
プログラムの処方箋~健康なコードと病んだコード
C++の話(本当にあった怖い話)
Ad

Similar to C++ Template Metaprogramming (13)

PDF
C++0x concept
PDF
C++0x 言語の未来を語る
PPTX
Lambda in template_final
PPTX
ナウなヤングにバカうけのイカしたタグ付き共用体
PDF
Replace Output Iterator and Extend Range JP
PDF
Python と型ヒント (Type Hints)
PDF
わんくま同盟大阪勉強会#61
PDF
boost tour 1.48.0 all
PDF
constexpr idioms
PDF
Boost tour 1_40_0
PDF
Emcpp item31
PDF
Emcjp item21
PDF
拡張可能でprintfっぽい書式指定ができて書式指定文字列と引数をコンパイル時に検証できる文字列フォーマット関数を作った
C++0x concept
C++0x 言語の未来を語る
Lambda in template_final
ナウなヤングにバカうけのイカしたタグ付き共用体
Replace Output Iterator and Extend Range JP
Python と型ヒント (Type Hints)
わんくま同盟大阪勉強会#61
boost tour 1.48.0 all
constexpr idioms
Boost tour 1_40_0
Emcpp item31
Emcjp item21
拡張可能でprintfっぽい書式指定ができて書式指定文字列と引数をコンパイル時に検証できる文字列フォーマット関数を作った

More from Akira Takahashi (20)

PPTX
Cpp20 overview language features
PDF
Cppmix 02
PPTX
Cppmix 01
PDF
Modern C++ Learning
PDF
cpprefjp documentation
PDF
Boost tour 1_61_0 merge
PDF
Boost tour 1_61_0
PDF
error handling using expected
PDF
Boost tour 1.60.0 merge
PDF
Boost tour 1.60.0
PDF
Boost container feature
PDF
Boost Tour 1_58_0 merge
PDF
Boost Tour 1_58_0
PDF
C++14 solve explicit_default_constructor
PDF
C++14 enum hash
PDF
Multi paradigm design
PDF
Start Concurrent
PDF
Programmer mind
PDF
Boost.Study 14 Opening
PDF
Executors and schedulers
Cpp20 overview language features
Cppmix 02
Cppmix 01
Modern C++ Learning
cpprefjp documentation
Boost tour 1_61_0 merge
Boost tour 1_61_0
error handling using expected
Boost tour 1.60.0 merge
Boost tour 1.60.0
Boost container feature
Boost Tour 1_58_0 merge
Boost Tour 1_58_0
C++14 solve explicit_default_constructor
C++14 enum hash
Multi paradigm design
Start Concurrent
Programmer mind
Boost.Study 14 Opening
Executors and schedulers

C++ Template Metaprogramming