Cleanest way for conditional code instantiation in C++ template

后端 未结 6 1589
深忆病人
深忆病人 2021-02-18 19:11

I\'m trying to get the following C++ code running:

#include 

template class ConditionalData {
};

template 

        
6条回答
  •  旧时难觅i
    2021-02-18 19:27

    You can use the preprocessor to 'generate' each variation of your class as template specializations.

    First, the 'template' header we will generate the specializations from:

    ATemplate.h
    //no include guards to allow multiple inclusion
    template<>
    class A
    {
    public:
        A()
        {
    #if A_HAS_DATA
            double data;
            if (hasdata) {
                data = sin(cos(123.4));
            }
    #endif
        }
    }
    

    Then we actually generate each specialization to obtain a normal header to use in your code:

    A.h
    #pragma once
    
    template
    class A;
    
    //Generate specialization for hasdata = true
    #define A_HAS_DATA 1
    #include "ATemplate.h"
    #undef A_HAS_DATA
    //(undef avoids redefinition warning)
    //Generate specialization for hasdata = false
    #define A_HAS_DATA 0
    #include "ATemplate.h"
    #undef A_HAS_DATA
    

    Essentially, instead of manually writing each specialization for each possible case (given that you might have multiple such settings to include/exclude stuff), we use preprocessor to generate each variant by including a header multiple times, each time with a different value for preprocessor define(s) to get different result.

    Prefer to use normal template approaches when they work, but if the amount of manual code duplication (to define all the possible variants) grows too high, this approach can work (as you can specify everything 'inline' akin what static if would do if we had one)

提交回复
热议问题