“模板多态性”当调用基类型的模板参数的函数时,使用派生类型? [英] "template polymorphism" when calling function for templated parameter of base type, with derived type?
问题描述
我有一个模板类:
template< class T&
class TemplateClass
{
//不相关这个类做什么
}
b $ b
有两个类,一个基类和一个派生自它的类:
class Base
pre>
{
//不管什么
}
类派生:public Base
{
}
现在我想组装一个函数,它可以处理模板类型为Base *的TemplateClass以及模板类型为Derived *的TemplateClass,而无需单独实现该函数两种类型。
在代码中,这是我想要做的:
void DoSomething(const TemplateClass< Base *>& tc)
pre>
{
// do something
}
和代码中的其他位置:
TemplateClass< Base *>一个;
TemplateClass< Derived *> b;
DoSomething(a); // Works
DoSomething(b); //不工作,但我想它工作
这不必手动重载DoSomething for Derived *?
解决方案很遗憾,C ++不支持模板协方差,所以你不能这样做自动。作为解决方法,您可以这样做:
template< typename T&
void DoSomething(const TemplateClass< T *>& tc){
//在C ++ 03中,使用BOOST_STATIC_ASSERT和boost :: is_convertible
static_assert(
std: :is_convertible< T *,Base *> :: value,
模板参数必须可转换为Base *
);
// ...
}
I've got a template class:
template <class T> class TemplateClass { //irrelevant what this class does }
And two classes, one base and one class which derives from it:
class Base { //does whatever } class Derived : public Base { }
Now I want to assemble a function which can deal with TemplateClass of templated type Base* as well as TemplateClass of templated type Derived* without having to implement the function separately for both types.
In code, this is what I'd like to be able to do:
void DoSomething(const TemplateClass<Base *> &tc) { //do something }
And somewhere else in the code:
TemplateClass<Base *> a; TemplateClass<Derived *> b; DoSomething(a); //Works DoSomething(b); //Doesn't work, but I'd like it to work
Is there a way to implement this without having to manualy overload DoSomething for Derived* ?
解决方案Sadly, C++ does not support template covariance, so you cannot do that automatically. As a workaround, you could do something like this:
template <typename T> void DoSomething(const TemplateClass<T*>& tc) { // in C++03, use BOOST_STATIC_ASSERT and boost::is_convertible static_assert( std::is_convertible<T*, Base*>::value, "Template argument must be convertible to Base*" ); // ... }
这篇关于“模板多态性”当调用基类型的模板参数的函数时,使用派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!