“template polymorphism” when calling function for templated parameter of base type, with derived type?

前端 未结 2 1583
抹茶落季
抹茶落季 2021-01-20 15:42

I\'ve got a template class:

template 
class TemplateClass
{
   //irrelevant what this class does
}

And two classes, one base

2条回答
  •  日久生厌
    2021-01-20 16:13

    Sadly, C++ does not support template covariance, so you cannot do that automatically. As a workaround, you could do something like this:

    template 
    void DoSomething(const TemplateClass& tc) {
        // in C++03, use BOOST_STATIC_ASSERT and boost::is_convertible
        static_assert(
            std::is_convertible::value,
            "Template argument must be convertible to Base*"
        );
    
        // ...
    }
    

    Demo on ideone.

提交回复
热议问题