I have a function template that I have specialized for a specific type. I'm having trouble getting the specialized version to be called in certain circumstances. To illustrate
struct Base {};
struct Derived : public Base {};
template <typename VALTYPE> void FooInternal(VALTYPE&)
{
std::cout << L"FooInternal template";
}
template<> void FooInternal(Base&)
{
std::cout << L"FooInternal SPECIAL";
}
Now if I construct an instance of "Base" or "Derived" and call "FooInternal", all works as I would expect
int _tmain(int argc, _TCHAR* argv[])
{
int x = 7;
FooInternal(x); // Calls FooInternal<VALTYPE>() template
Base b;
FooIntenral(b); // Calls FooInternal<Base>() specialization
Derived d;
FooInternal(d); // Calls FooInternal<Base>() specialization
return 0;
}
The output of this is
FooInternal template
FooInternal SPECIAL
FooInternal SPECIAL
}
But suppose I have an intermediate function template between these two that calls FooInternal. In this case, the template resolution for the derived type seems to fail along the way
// Intermediate template. Just calls FooInternal.
template<typename VALTYPE>
void Foo(VALTYPE& val)
{
FooInternal<VALTYPE>(val);
}
// Now repeat the same 3 calls and see what happens with Derived...
int _tmain(int argc, _TCHAR* argv[])
{
int x = 7;
Foo(x); // Calls FooInternal<VALTYPE>() template
Base b;
Foo(b); // Calls FooInternal<Base>() specialization
Derived d;
Foo(d); // Calls FooInternal<VALTYPE>() template!!!
return 0;
}
The output of this program is
FooInternal template
FooInternal SPECIAL
FooInternal template
I can't understand why -- in the 3rd call "Foo" will not then call the specialized version of FooInternal as it did when the call was direct. Shouldn't the compiler understand that is derived from 'Base' in this case? What rule am I missing here?
I am using Microsoft Visual Studio 2012 Update 3, if that matters.
-Joe