Cleanest way for conditional code instantiation in C++ template

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

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

#include 

template class ConditionalData {
};

template 

        
6条回答
  •  囚心锁ツ
    2021-02-18 19:27

    If you cannot(/don't want to) change ConditionalData, you may create 2 methods instead:

    template
    void SetData(ConditionalData& , const T& ) {/* Nothing */}
    
    template
    void SetData(ConditionalData& c, const T& value) { c.setData(value); }
    

    and then

    A() {
        ConditionalData data;
        SetData(data, 3);
    }
    

    For more complex cases

    template
    void A_impl_part1(ConditionalData&) {/* Nothing */}
    
    template
    void A_impl_part1(ConditionalData& c) { c.setData(3); }
    

    and then

    A() {
        ConditionalData data;
        A_impl_part1(data);
        // common part
        // A_impl_part2(data); // and so on
    }
    

提交回复
热议问题