Using dynamic_cast with templates

when implementing the factory template in C ++, I created the following function allocatorto create an instance of this child class:

template<class ChildClass, class ParentClass>
ParentClass* allocator() {
   ChildClass *child  = new ChildClass();
   ParentClass*parent = dynamic_cast<ParentClass*>(child);
   if(NULL==parent) {
     delete child;
     return NULL;
   }
   return parent;
}

everything works fine, but when you run the code using static code analysis tools such as coverity , the line is delete child;marked as logically dead code.

the reason that I am checking the execution is to assert what ChildClasscomes from ParentClass.

Now I understand that during the extension of the template, the compiler already knows whether it is obtained ChildClassfrom ParentClassand what dynamic_castis evaluated only at runtime.

, ChildClass ParentClass ( dynamic_cast non-NULL, ChildClass ).

, , ChildClass ParentClass ( )?

afaik, ++, - .

, (, ++ - , Visual Studio 6), , C++11 -features

+4
2

std::is_base_of:

constexpr bool is_base = std::is_base_of<ParentClass, ChildClass>::value;

static_assert, , ChildClass ParentClass.

static_assert(std::is_base_of<ParentClass, ChildClass>::value,
              "ParentClass is not base of ChildClass");

++ 11, boost::is_base_of BOOST_STATIC_ASSERT.

+6

"Derived" "Base" , a "Derived" "Base" . :.

void AssignToBase(Derived* derived) {
  Base* base = derived;
} 

... , "Derived" "Base" . SFINAE ( ++ 11 Boost) , . juanchopanza, ++ 11 std:: is_base_of < > , .

+2

Source: https://habr.com/ru/post/1539403/


All Articles