C++ template instantiation: Avoiding long switches

前端 未结 10 1171
轻奢々
轻奢々 2020-12-08 21:33

I have a class depending on an integer template parameter. At one point in my program I want to use one instantiation of this template, depending on a value of this paramet

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 22:10

    just use macros!

    template
    struct Wrapper {
        int content[A];
        void foo() { };
    };
    
    #define WRAPPER_SWITCH_CASE(i) case i: Wrapper().foo(); break;
    
    int main(int argc, char *argv[])
    {
        std::string arg = argv[1];
        int arg_int = std::stoi(arg);
    
        switch (arg_int) {
            WRAPPER_SWITCH_CASE(1)
            WRAPPER_SWITCH_CASE(2)
            WRAPPER_SWITCH_CASE(3)
            default: return 1;
        };
    
        return 0;
    }
    

    (live example)

    But as you know, macros are harmful; I think Wrapper should be allocate content at runtime, not template.

提交回复
热议问题