combining polymorphism and templates

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux