My question is very similar to this one, but I'm not sure if the same answers apply here.
I have a templated function whose code is relatively heavy, therefore I am defining it in a separate .cpp file and instantiating it explicitly for the types I need:
foo.h
template <typename T>
void foo(T &arg);
foo.cpp
template <typename T>
void foo(T &arg)
{
... //Long code
}
template
void foo<Type1>(Type1 &arg);
template
void foo<Type2>(Type2 &arg);
Now I would like to also be able to call foo()
on Type3
objects, with Type3
a derived class from Type2
. I can do this without issues with a non-templated function, but the templated one has linker issues:
class Type3 : public Type2
{ ... }
void foo1(Type2 &arg)
{ ... }
...
Type3 var;
foo1(var); //Runs fine
foo(var); //Linker error
Since I explicitly instantiated foo()
to accept Type2
variables, I don't really get why the same conversion from derived to base wouldn't automatically apply as it does for non-templated functions...
I know I can make this code run by writing foo<Type2>(var)
or foo((Type2&)var)
, but would there be a solution that doesn't need to change the way I call the function, and doesn't need explicitly instantiating foo
to accept Type3
variables (to avoid increasing compile time)?