Resolve enum template parameters at run-time

后端 未结 1 1343
庸人自扰
庸人自扰 2021-01-26 04:34

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

相关标签:
1条回答
  • 2021-01-26 05:15

    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);
    
    0 讨论(0)
提交回复
热议问题