I am trying to come up with a piece of logic that takes multiple enums and determine a struct type and its corresponding size to pass to a third-party component, and I am consid
You cant do this at run-time using templates, but you do have some other options you can use localise the changes.
My preference would be to use polymorphism:
class Foo {
static Foo* createFoo(FOO_TYPE type) {
switch(type) {
case FOO_TYPE_0:
return new FooType0();
case FOO_TYPE_1:
return new FooType1();
}
virtual void callFunction(ThridParty thirdParty)=0;
}
class FooType0 : public Foo {
void callFunction(ThridParty thirdParty) {
FOO_0 Foo = {};
UINT size = sizeof(Foo);
m_thirdParty->CallFunction(&Foo, size);
}
}
class FooType1 : public Foo {
void callFunction(ThridParty thirdParty) {
FOO_1 Foo = {};
UINT size = sizeof(Foo);
m_thirdParty->CallFunction(&Foo, size);
}
}
Your switch block would then become:
// Note this leaks ... see below for non-leaking version.
createFoo(m_foo)->callFunction(m_thirdParty);
Now there's some ugly duplication in each of the FooTypeX classes, so you can remove that with templatization:
class Foo {
static Foo* createFoo(FOO_TYPE type) {
switch(type) {
case FOO_TYPE_0:
return new FooX<FOO_1>();
case FOO_TYPE_1:
return new FooX<FOO_2>();
}
virtual void callFunction(ThridParty thirdParty)=0;
}
class FooX<BaseStruct> : public Foo {
void callFunction(ThridParty thirdParty) {
BaseStruct foo = {};
UINT size = sizeof(foo);
m_thirdParty->CallFunction(&foo, size);
}
}
// A bit of a hack to prevent leaking. In real code you may want to
// handle ownership differently.
std::unique_ptr<Foo>(createFoo(m_foo))->callFunction(m_thirdParty);