Click to See Complete Forum and Search --> : Generic Programming


Michello
May 31st, 2002, 01:21 PM
Hello there!

Are there any opportunities of generic programming in C++ without using templates?

My problem is, that I have to call a member function defined in a derived class from its base class with a function pointer like


(pDerivedClass->*pMsgFxn)();

Therefore I register the member function with a protected template member of the base class:


template <class T> bool RegisterFxn( T* pDerivedClass, void( T::* pMsgFxn )() );

Unfortunately I'm using DLLs and in this context templates are only generated when they're used and compiled in the type they're called. So any dummy calls of this template in the DLL, in order to generate code, won't work, because I don't know the type - the name - of possible derived classes.

So how can I solve the problem without using templates? How can I call a function without knowing its type?

Thanks in advance.

Michello

jfaust
May 31st, 2002, 02:27 PM
I've used template functions in a DLL, much like you are, to register a callback function within a class. It does work.

You do need to put the full body of and template methods inlined in the header file.

Jeff

Michello
May 31st, 2002, 02:49 PM
Thank you Jeff.

What I wanna realize are some message methods on a windows callback function in a DLL. I guess I've to look closer to my code now. :rolleyes:

Michello

Michello
June 1st, 2002, 08:20 AM
Ok Jeff, you're right. A template member function doesn't need to be implemented in the header, also any member function of a template class. But this doesn't work with virtual functions, for example:

//...

#define DLL_EXPORT __declspec( dllexport )

//...

class DLL_EXPORT Base
{
//...

virtual void Fxn()
{}

//...
};

template <class T> class DLL_EXPORT Derived : public Base
{
//...

void Fxn()
{
// Its body has to be here, otherwise: unresolved external!
}

void AnotherFxn(); // Implement wherever you want to!

//...
};

Can anybody explain me this context?

Thanks in advance!

Michello

jfaust
June 1st, 2002, 12:06 PM
Actually, my comment was that template methods should be implemented in the header. I wasn't aware of any different behavior with virtual methods. But I do know that any method that actually uses the template parameter needs to be inlined in the header.

templates are incredibly difficult to implement for a compiler, which is why many languages (hrmm... Java) haven't done so. Even with C++, all compilers are not created equal. The sun compiler has serious problems. There are many flaky behaviors with templates, especially if you start throwing in other variables like DLLs or virtual methods.

So, expect to make some compromises.

Jeff