I suspect that the answer to this is "no" or "you're doing it wrong," but:
Is it possible to implement interface-type behavior WITHOUT using inheritance in C++ (11, if it matters)?
I have a couple of different structs,
struct Foo
{
float A;
void Bind()
{ .... }
};
struct Bar
{
float B;
void Bind()
{
}
};
... and others
These are operated on by a method that passes arrays of these structs to another process, and they have to be pretty tightly packed. If I use inheritance, creating a base class that implements the ::Bind()
method, then the descendent classes have not only their data, but a VMT, which consumes a significant chunk of a very scarce resource. Other methods need to operate on these different types, but don't really care about the data members or the specifics of the ::Bind()
method, which differs greatly between types.
In C# (or, I suspect, java), I'd do something like:
interface ICommon
{
void Bind();
}
struct Foo : ICommon
{
void Bind() { .... };
};
struct Bar : ICommon
{
void Bind() { ..... }
}
I could use a template:
template<typename T>
void Bind(T &item)
{
item.Bind();
}
but this introduces some constraint (ie, template needs to be declared in a header rather than a cpp, etc.) that are less than ideal. I'm aware of some hacks that let you put a template method implementation in the cpp file, but they're kind of messy and I'd rather avoid it.
This may be a "have your cake and eat it, too" request.
(Note that this isn't really a duplicate of other C++ Interfaces questions as I'm trying to avoid the oft-recommended solution of using multiple inheritance.)