OSDN Git Service

instance_counter のコメントを微修正
[gintenlib/gintenlib.git] / gintenlib / cast.hpp
1 #ifndef GINTENLIB_INCLUDED_CAST_HPP_
2 #define GINTENLIB_INCLUDED_CAST_HPP_
3
4 /*
5
6       <gintenlib/cast.hpp>
7
8   cast : 明示的な暗黙キャスト
9
10   宣言&定義:
11     // 引数をそのまま返す
12     template<typename T>
13     inline T cast( typename call_traits<T>::param_type x ) { return x; }
14
15   機能:
16     暗黙変換を明示的に行うためのキャストです。 cast<void*>( 0 ) のように使います。
17     主に多重定義された関数の呼び出しを制御するときに使います。
18     Boost にも implicit_cast という同機能のキャストがありますが、
19     こちらのほうが文字数が少ないという点で利点があります。
20
21   使用例:
22     void hoge( int ){ cout << "int 版です\n"; }
23     void hoge( void* ){ cout << "void* 版です\n"; }
24     
25     // クラスに対して
26     // noncopyable なクラスにしておく
27     class base : boost::noncopyable {};
28     struct derived : base {};
29     
30     void fuga( base& ){ cout << "base& 版です\n"; }
31     void fuga( derived& ){ cout << "derived& 版です\n"; }
32
33     int main()
34     {
35       // 予め using 宣言すれば四文字で使えて幸せ
36       using gintenlib::cast;
37       
38       hoge( 0 ); // int 版
39       hoge( cast<void*>(0) ); // void* 版。static_cast<void*>(0) でもOKだが長い
40       
41       derived x;  // あるいは base x;
42       fuga( x );  // デフォルト呼び出し
43       fuga( cast<base&>(x)    );  // base& 版。
44       fuga( cast<derived&>(x) );  // derived& 版。base x; の場合はコンパイルエラー
45                                   // static_cast だと、コンパイルエラーにならない
46     }
47
48   補足:
49     ・暗黙変換を明示的にやって何が楽しいかといえば・・・使用例を見てください。これが全てです。
50     ・このように、関数の多重定義やテンプレートに対し、正しいものを指定するときに使えます。
51     ・static_cast との違いは、 Source の型が暗黙的に Target に変換できる時だけキャストできる点。
52     ・まぁ普通は static_cast でも十分なんですが、クラスの継承とかを使うと、やっぱり危険なので。
53     ・少し前までの実装は boost::enable_if を使っていましたが、修正されました。
54     ・boost::call_traits さえ動けば動きます。
55
56 */
57
58 #include "call_traits.hpp"
59
60 namespace gintenlib
61 {
62   // 暗黙キャスト関数
63   template<typename T>
64   inline T cast( typename call_traits<T>::param_type x )
65   {
66     return x;
67   }
68
69 }   // namespace gintenlib
70
71
72 #endif  // #ifndef GINTENLIB_INCLUDED_CAST_HPP_