如何强制模板化匹配基类? [英] How do you force a templatization to match a base class?

查看:149
本文介绍了如何强制模板化匹配基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板函数显式实例化 Base 类,但不是 Derived 类。如何强制传递 Derived 类(或其他派生类)的用法与 Base 类匹配?



头文件:

  class Base {
} ;
class Derived:public Base {
};
class Derived2:public Base {
};

template< typename Example> void function(Example& arg);

执行文件:

  //显式实例化基类:
template void function< Base>(Base& arg);

//定义模板函数:
template< typename Example> void function(Example& arg){
//做某事。因为我没有为显式实例化函数> Derived <$ c $ b>


$ b
Derived2 ,我得到未定义的引用,但是我想绑定到 Base



如何强制模板使用C ++ - 03从Base派生到Base的所有对象解析为Base类?



我可以通过将 Derived 类专门化到 Base 类定义

解决方案

如何:

 code> template<> void function(Derived& arg)
{
function< Base>(arg);
}

编辑:您也可以使用函数重载来执行此操作, aschepler 已建议:

  void function(Derived& arg)
{
function& Base>(arg);
}

这在概念上是一样的, p>

I have a template function which is explicitly instantiated for Base class, but not for Derived class. How can I force the uses that pass a Derived class (or other derived classes) to match against the Base class?

Header file:

class Base {
};
class Derived : public Base {
};
class Derived2 : public Base {
};

template <typename Example> void function(Example &arg);

Implementation file:

// Explicitly instantiate Base class:
template void function<Base>(Base &arg);

// Define the template function:
template <typename Example> void function(Example &arg) {
  // Do something.
}

Because I have not explicitly instantiated function for Derived or Derived2, I get undefined references, however, I would like to bind against the Base class which is explicitly defined.

How can I force the template to resolve to the Base class for all objects derived from Base using C++-03?

Can I do it somehow with a specialization of the Derived class to the Base class definition?

解决方案

How about:

template <> void function(Derived &arg)
{
     function<Base>( arg );
}

EDIT: You can also do this with function overloading, as aschepler has suggested:

void function(Derived &arg)
{
     function<Base>( arg );
}

It's conceptually the same, although, I agree, slightly better :)

这篇关于如何强制模板化匹配基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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