I have two template class, and the Leaf<T>
is derived from the Base<T>
, then I developed a template function which uses the reference of the Base<T>
as its parameter. And set the definition and the instantiation of that function in its source file.
The issue happened once I tried to pass the Leaf<T>
as the argument of that function. The compiler tries to find the symbol with Leaf<T>
without the auto convention as it used to be.
// foo.h
#ifndef __FOO_H_INCLUDED__
#define __FOO_H_INCLUDED__
#include <base.h>
template <typename T>
void Foo(T &value);
#endif // __FOO_H_INCLUDED__
// foo.cpp
#include <foo.h>
#include <iostream>
template <typename T>
void Foo(T &value)
{
std::cout<<value.getValue()<<std::endl;
}
template void Foo(MyBase<int> &value);
// main.cpp
#include <leaf.h>
#include <foo.h>
int main()
{
int i = 20;
MyLeaf<int> leaf;
leaf.setValue(i);
Foo(leaf);
}
The above snippet will throw an "undefined reference" exception in linking. Refactor the invoking as Foo<MyBase<int> >(leaf)
will fix the issue but that not what I want. And explicitly instantiate all of the potential derived types is also impossible because there is no way to know how many are them.
So is there a way that could make the linker recognize my symbols with the base type rather than find the precise one and throw an error?