Prevent user from deriving from incorrect CRTP base

前端 未结 6 897
感动是毒
感动是毒 2020-12-14 01:53

I cannot think about a proper question title to describe the problem. Hopefully the details below explains my problem clear.

Consider the following code



        
6条回答
  •  孤城傲影
    2020-12-14 02:24

    If you can't count with C++11, you could try this trick:

    1. Add a static function in Base that returns a pointer to its specialied type:

      static Derived *derived( ) { return NULL; }

    2. Add a static check function template to base that takes a pointer:

      template< typename T > static bool check( T *derived_this ) { return ( derived_this == Base< Derived >::derived( ) ); }

    3. In your Dn constructors, call check( this ):

      check( this )

    Now if you try to compile:

    $ g++ -Wall check_inherit.cpp -o check_inherit
    check_inherit.cpp: In instantiation of ‘static bool Base::check(T*) [with T = D2; Derived = D1]’:
    check_inherit.cpp:46:16:   required from here
    check_inherit.cpp:19:62: error: comparison between distinct pointer types ‘D2*’ and ‘D1*’ lacks a cast                                                                                                                             
    check_inherit.cpp: In static member function ‘static bool Base::check(T*) [with T = D2; Derived = D1]’:                                                                                                                   
    check_inherit.cpp:20:5: warning: control reaches end of non-void function [-Wreturn-type]                                                                                                                                          
    

提交回复
热议问题