How do you force a templatization to match a base class?

大城市里の小女人 提交于 2019-12-10 12:14:32

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/14612410/how-do-you-force-a-templatization-to-match-a-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!