[C++11]static_assert(コンパイル時エラー検出)とtype_traits |
2014年11月22日23:03:15 |
|
メタ(テンプレートを使った)プログラミングを加速する為にstatic_assertは導入したいものです。
これまでテンプレートを利用した関数は実行時まで挙動がどうなるか分かりませんでした。
変な出力を返す事もあれば、落ちることもあります。
そこで活用したいのがstatic_assertです!
単体では役に立たないのでtype_traitsと呼ばれる型をチェックする機能との併せ技になります。 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| #include <type_traits>
#include <cstdio>
template <class T>
void Print( T data )
{
static_assert( std::is_same<T,int>::value, "NotSuppurtType" );
printf( "%d\n", data );
}
Print(0);
Print('\0');
Print(0.0f);
|
コンパイル時に判別が出来て非常に便利ですね!
type_traitsには様々な判定方法があるので詳しく知りたい方は
リファレンスを見るか丁寧に解説されているサイトをご覧下さい。
さて上記サンプルは%dで出力したいだけなので整数なら何でもよかったりします。
整数と実数の判定が用意されているので書き換えてみます。 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| #include <type_traits>
#include <cstdio>
template <class T>
void Print( T data )
{
static_assert( std::is_integral<T>::value, "NotSuppurtType" );
printf( "%d\n", data );
}
Print(0);
Print('\0');
Print(0.0f); |
実数判定の場合 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| #include <type_traits>
#include <cstdio>
template <class T>
void Print( T data )
{
static_assert( std::is_floating_point<T>::value, "NotSuppurtType" );
printf( "%f\n", data );
}
Print(0);
Print('\0');
Print(0.0f); |
最後に注意点です。
型を知るための類似機能としてtypeid演算子がありますが
こちらは実行時型情報の機能なのでstatic_assertの中に混ぜて利用することは出来ません。
間違いやすいポイントだと思うのでご留意下さい。
ちなみにsizeof演算子はコンパイル時にサイズが分かるのでこちらは使えます。 |
|