This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
combining polymorphism and templates
- From: "Matt Brown" <deadguysfrom at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Wed, 26 Sep 2007 14:41:48 -0700
- Subject: combining polymorphism and templates
I know this may be an abuse of either/both polymorphism and templates,
but this is what I'm trying to do:
/************************* test.cpp *************************************/
#include <iostream>
using std::cout;
class base {
public:
virtual ~base() {}
};
class derived : public base {};
class derived2 : public base {};
class derived3 : public derived {};
class generic_functor
{
public:
template <typename T>
void operator()(T * t) { std::cout << "generic functor\n"; }
};
template <>
void generic_functor::operator()<int>(int * i) { cout << "int functor\n"; }
template <>
void generic_functor::operator()<base>(base * b) { cout << "base functor\n"; }
template <>
void generic_functor::operator()<derived>(derived * d) { cout <<
"derived functor\n"; }
int main(void)
{
int i = 0;
float f = 0.0;
base b;
derived d;
derived2 d2;
derived3 d3;
generic_functor functor;
cout << "int: "; functor(&i);
cout << "float: "; functor(&f);
cout << "base: "; functor(&b);
cout << "derived: "; functor(&d);
cout << "derived2: "; functor(&d2);
cout << "derived3: "; functor(&d3);
return 0;
}
/************************* end test.cpp *************************************/
The output I get is:
int: int functor
float: generic functor
base: base functor
derived: derived functor
derived2: generic functor
derived3: generic functor
Which is what I want/expect except for the last line of output. I want:
derived3: derived functor
This seems like a reasonable enough desire to me. Am I doing
something wrong? If it can't be done, why not?
thanks
-matt