2015/03/30

静的多様性で書くとき、派生した型を指定しない。

ふと思いついてこんなのを作ってみた。

  1
  2 #include
  3
  4 template < typename Derived >
  5 class Base
  6 {
  7 public:
  8         Base() {}
  9         ~Base() {}
 10         int set()
 11         {
 12                 return ( static_cast(this)->setImpl() );
 13         }
 14 };
 15
 16 template< typename data_t >
 17 class DerivedClass : public Base< DerivedClass >
 18 {
 19 public:
 20         DerivedClass() {}
 21         ~DerivedClass() {}
 22         setImpl()
 23         {
 24                 std::cout << "seImpl() called"  << std::endl;
 25         }
 26 };
 27
 28 int main ()
 29 {
 30         Base< DerivedClass > *b;
 31         b->set();
 32         return 0;
 33 }


30行目の*bはDerivedClass型になる。std::vectorが遅いので自分で作り中に気づいた。

0 件のコメント:

コメントを投稿

まとめページ

      

リンク

The Wizard of Science
友達のブログ文化人類学とか難しい話をしております。あとホームページから自作ゲームも配布。