1

I'm wanting to invoke a specialized templated function by using a pointer to it's base type. I'm not sure if this possible so I'm open to suggestions and/or alternatives. Here is an example of my situation:

class CBase {};
class CDerivedClass : public CBase {};

template<class T>
int func<T>(T &x) { ... };

template<>
int func<CDerivedClass>(CDerivedClass &x) { ... };

I have another function that manages a list of CBase pointers and then calls the func() function.

void doStuff()
{
    CBase *foo[10] = { ...... };

    for (int i = 0; i < 10; ++i)
        func(*foo[i]);
}

Is there a way to get the derived type, so that func(CDerivedClass &) is called?

MarkP
  • 4,168
  • 10
  • 43
  • 84
  • That's what virtual functions are for. – K-ballo Oct 02 '11 at 16:28
  • 1
    That would mean that the logic of func() will be directly coupled to the classes. I don't want that. – MarkP Oct 02 '11 at 16:29
  • @MarkP: Huh? what do you mean? – jalf Oct 02 '11 at 16:34
  • @MarkP: `dynamic_cast` then... – K-ballo Oct 02 '11 at 16:37
  • possible duplicate of [Matching an overloaded function to its polymorphic argument](http://stackoverflow.com/questions/6897662/matching-an-overloaded-function-to-its-polymorphic-argument), also good information at [Visitor and templated virtual methods](http://stackoverflow.com/q/2886193/103167) – Ben Voigt Oct 02 '11 at 16:40

3 Answers3

1

What about Template Subclassing? This idiom allows you to use compile-time polymorphism in C++. The cost of it is higher verbosity (such as specifying the whole class hierarchy up to the current class). In your case:

template <typename TSpec> class Klass {};

template <typename TSpec> struct SpecTag {};
template <typename TSpec> class Klass<SpecTag<TSpec> > {};

template <typename TSpec>
int func(Klass<TSpec> &x) { ... };

template <typename TSpec>
int func(Klass<SpecTag<TSpec> > &x) { ... };
Manuel
  • 6,461
  • 7
  • 40
  • 54
0

Alternative solution : from your example, it's obvious that you just should to use a virtual method in CBase, so you just have to define a virtual function in CBase and an overriding function in the derived class.

cJ Zougloub
  • 1,484
  • 10
  • 19
0

The "Visitor" pattern comes to the rescue in this case. It enables polymorphic behavior in an algorithm implemented outside the class. Some support code is required inside the class, but new algorithms can later be added, existing algorithms modified, etc., without affecting the class.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720