Any metaprogramming way to generate overloads for various numbers of template parameters?

后端 未结 4 1187
野趣味
野趣味 2020-12-18 03:17

I\'m trying to create a set of function templates that can take different types and numbers of parameters, like this:

template 
void call(T0 arg0);         


        
4条回答
  •  旧巷少年郎
    2020-12-18 03:35

    Here's how I make variadic templates in my code, without C++0x support and with Boost (very abridged):

    // blah.hpp
    // (include guards)
    
    #ifndef BLAH_MAX_PARAMETERS
        // allow this to be changed to a higher number if needed,
        // ten is a good default number
        #define BLAH_MAX_PARAMETERS 10
    #endif
    
    #if BLAH_MAX_PARAMETERS < 0
        // but don't be stupid with it
        #error "Invalid BLAH_MAX_PARAMETERS value."
    #endif
    
    // include premade functions, to avoid the costly iteration
    #include "detail/blah_premade.hpp"
    
    // generate classes if needed
    #if BLAH_MAX_PARAMETERS > BLAH_PREMADE_PARAMETERS
        #define BOOST_PP_ITERATION_LIMITS (BOSST_PP_INC(BLAH_PREMADE_PARAMETERS), \
                                            BLAH_MAX_PARAMETERS)
        #define BOOST_PP_FILENAME_1 "detail/blah.hpp"
        #include BOOST_PP_ITERATE()
    #endif
    

    That's the "main" include. As you can see, it just sets up the number of iterations desired, and makes sure that enough exist. I include a premade file because this iteration (especially when used multiple times) can really add to your compile time. I premake up to ten, so by default no iteration is done:

    // detail/blah_premade.hpp
    // (include guards)
    
    // a bunch of manually made (however you want to do that)
    // pastes of what our iteration normally generates
    
    // allow this file to change the assumed count
    #define BLAH_PREMADE_PARAMETERS 10
    

    Then we have our preprocessor template:

    // detail/blah.hpp
    // no header guards
    
    #define N BOOST_PP_ITERATION()
    
    // use N to generate code
    
    #undef
    

    And that's it. I leave it to you to fill in the middle for whatever you want; perhaps check out Xeo's answer.

提交回复
热议问题