How can I specialize a C++ template for a range of integer values?

后端 未结 4 843
离开以前
离开以前 2020-12-07 22:51

Is there a way to have a template specialization based on a range of values instead of just one? I know the following code is not valid C++ code but it shows what I would li

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 23:46

    Try std::conditional:

    #include 
    
    template
    class circular_buffer {
    
        typedef typename
            std::conditional< SIZE < 256,
                              unsigned char,
                              unsigned int
                            >::type
            index_type;
    
        unsigned char buffer[SIZE];
        index_type head;
        index_type tail;
    };
    

    If your compiler doesn't yet support this part of C++11, there's equivalent in boost libraries.

    Then again, it's easy to roll your own (credit goes to KerrekSB):

    template 
    struct conditional {
        typedef T type;
    };
    
    template   // partial specialization on first argument
    struct conditional {
        typedef F type;
    }; 
    

提交回复
热议问题