“模板多态性”当调用基类型的模板参数的函数时,使用派生类型? [英] "template polymorphism" when calling function for templated parameter of base type, with derived type?

查看:175
本文介绍了“模板多态性”当调用基类型的模板参数的函数时,使用派生类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类:

  template< class T& 
class TemplateClass
{
//不相关这个类做什么
}


b $ b

有两个类,一个基类和一个派生自它的类:

  class Base 
{
//不管什么
}

类派生:public Base
{
}
pre>

现在我想组装一个函数,它可以处理模板类型为Base *的TemplateClass以及模板类型为Derived *的TemplateClass,而无需单独实现该函数两种类型。



在代码中,这是我想要做的:

  void DoSomething(const TemplateClass< Base *>& tc)
{
// do something
}
pre>

和代码中的其他位置:

  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 *
);

// ...
}

在ideone上演示


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*"
    );

    // ...
}

Demo on ideone.

这篇关于“模板多态性”当调用基类型的模板参数的函数时,使用派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆