1 #ifndef GINTENLIB_INCLUDED_CAST_HPP_
2 #define GINTENLIB_INCLUDED_CAST_HPP_
13 inline T cast( typename call_traits<T>::param_type x ) { return x; }
16 暗黙変換を明示的に行うためのキャストです。 cast<void*>( 0 ) のように使います。
17 主に多重定義された関数の呼び出しを制御するときに使います。
18 Boost にも implicit_cast という同機能のキャストがありますが、
19 こちらのほうが文字数が少ないという点で利点があります。
22 void hoge( int ){ cout << "int 版です\n"; }
23 void hoge( void* ){ cout << "void* 版です\n"; }
26 // noncopyable なクラスにしておく
27 class base : boost::noncopyable {};
28 struct derived : base {};
30 void fuga( base& ){ cout << "base& 版です\n"; }
31 void fuga( derived& ){ cout << "derived& 版です\n"; }
35 // 予め using 宣言すれば四文字で使えて幸せ
36 using gintenlib::cast;
39 hoge( cast<void*>(0) ); // void* 版。static_cast<void*>(0) でもOKだが長い
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 だと、コンパイルエラーにならない
49 ・暗黙変換を明示的にやって何が楽しいかといえば・・・使用例を見てください。これが全てです。
50 ・このように、関数の多重定義やテンプレートに対し、正しいものを指定するときに使えます。
51 ・static_cast との違いは、 Source の型が暗黙的に Target に変換できる時だけキャストできる点。
52 ・まぁ普通は static_cast でも十分なんですが、クラスの継承とかを使うと、やっぱり危険なので。
53 ・少し前までの実装は boost::enable_if を使っていましたが、修正されました。
54 ・boost::call_traits さえ動けば動きます。
58 #include "call_traits.hpp"
64 inline T cast( typename call_traits<T>::param_type x )
69 } // namespace gintenlib
72 #endif // #ifndef GINTENLIB_INCLUDED_CAST_HPP_