C++ template instantiation: Avoiding long switches

前端 未结 10 1174
轻奢々
轻奢々 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 21:50

    You could use a variadic template, maybe like this:

    #include 
    #include 
    
    int main(int argc, char * argv[])
    {
        if (argc != 2) { return EXIT_FAILURE; }
    
        handle_cases<1, 3, 4, 9, 11>(std::stoi(argv[1]));
    }
    

    Implementation:

    template  struct IntList {};
    
    void handle_cases(int, IntList<>) { /* "default case" */ }
    
    template  void handle_cases(int i, IntList)
    {
        if (I != i) { return handle_cases(i, IntList()); }
    
        Wrapper w;
        w.foo();
    }
    
    template  void handle_cases(int i)
    {
        handle_cases(i, IntList());
    }
    

提交回复
热议问题