Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top