Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// Overriding a member method of a template class/struct by defining a specialized implementation.
//
#include <cstdio>
#include <typeinfo>
template<typename T>
struct Foo
{
void bar()
{
std::printf("Base Foo<%s>::bar()\n", typeid(T).name());
}
};
template<>
void Foo<int>::bar()
{
std::printf("Specialized Foo<int>::bar()\n");
}
template<>
void Foo<float>::bar()
{
std::printf("Specialized Foo<float>::bar()\n");
}
int main()
{
Foo<char> cFoo;
Foo<int> iFoo;
Foo<float> fFoo;
cFoo.bar(); // Base implementation
iFoo.bar(); // Specialized
fFoo.bar(); // Specialized
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment