Re: Compile-time polymorphism of "interfaces"
Andrew Schweitzer wrote:
Compile-time polymorphism newbie question here. We are using virtual
functions and getting a performance hit in a device driver. Can some
suggest a way to implement this with templates? We don't actually need
run-time polymorphism, but we do want to share a bunch of code at
compile time.
I'll try to sketch some equivalents/conversions....
class IInterface1{public: virtual void DoSomething() = 0;};
class IInterface2{public: virtual void DoSomethingElse() = 0;};
These don't have any equivalents in code, only maybe in the documentation.
The interface is checked by the template code using this by simply using
this. If the required interface isn't present, you get compile errors.
class Dervied1 : public virtual IInterface1{
int m_i;
IInterface2* m_pII2;
public:
virtual void DoSomething() {m_i++;}
void UseInterface(){m_pII2->DoSomethingElse();}
}
Here, you would simply make a class that contains 'm_i' and defines
DoSomething(). Note that this will be a simple class, which can be one of
many you could inherit.
To be honest, I don't understand how the use of IInterface2 comes to play
here.
class Dervied1v2 : public virtual IInterface1{
int m_i;
IInterface2* m_pII2;
public:
virtual void DoSomething() {m_i++;}
void UseInterface(){m_pII2->DoSomethingElse();}
}
This is exactly the same as Dervied1, what is the point your'e trying to
make?
class Dervied2 : public virtual IInterface1{
int m_i;
IInterface1* m_pII1; //Might be a Derived1 or a Derived1v2, but it
would be nice
//to figure out at compile time and
get rid of virtual.
public:
virtual void DoSomethingElse() {m_i++;}
void UseInterface(){m_pII2->DoSomething();}
}
Okay, if you want to fix the real type of m_pII1 at compile time, I'd
suggest making this class a template parametrised on that type. I'd also
suggest not using pointers but simple containment.
The ways I thought of to do this with templates all seemed to have
circular definitions.
It shouldn't, though I'm not yet clear what exactly your issues are.
One thing btw: As I said, I'm not exactly clear what your design looks like,
so it's hard to suggest the right thing.
You said you wanted to reuse code. Well, this can be achieved by e.g.
putting that code into a baseclass. The final class then inherits the
baseclasses it needs. If this baseclass needs to call code in the derived
class (like a virtual function call), you can resolve this using a
technique called 'CRTP'.
Lastly, you mention you have performance overhead issues. You say that was
because of virtual functions, but I wonder if that is really just because
of that or maybe also related to the fact that you use pointers, which
represent another bit of indirection.
I hope I gave you some suggestions, otherwise you will have to clarify your
examples a bit.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]