Cleanest way for conditional code instantiation in C++ template

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

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

#include 

template class ConditionalData {
};

template 

        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-18 19:32

    First of all, you don't require 3 versions of class ConditionalData, because bool can be either true or false. So let me simplify it as following:

    template class ConditionalData {
    };                 //^^^^^^^^^^^^
    
    template  class ConditionalData {
    private:
        T data;
    public:
        void setData(T _data) { data = _data; }
    };
    

    Secondly, to answer your question: Whichever members are falling for false category, just overload them outside the class body as following:

    template class A { 
    public:
        A() {
            ConditionalData data;
            if (hasdata) {
                data.setData(3);
            }
        }   
    };
    
    template<> A::A() {}  // Does nothing for `false` condition
    

提交回复
热议问题