Cleanest way for conditional code instantiation in C++ template

后端 未结 6 1561
深忆病人
深忆病人 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:32

    This is a common pattern, so there's actually a paper to add constexpr_if to C++. If that makes it in to future versions, it would allow you to keep your code pretty much as-is.

    template class A {
    public:
        A() {
            ConditionalData data;
            constexpr_if (hasdata) {
            //^^^^^^^^^^ instead of plain if
                data.setData(3);
            }
        }
    };
    

    For now, you'll need to make do with one of the other answers.


    Edit: This was added to C++17 and called if constexpr

提交回复
热议问题