enum class 用二元运算符扩展的可变参数包

enum class varidic parameter pack to expand with binary operator

有一个 class 模板用作枚举 class 标志容器:

template<typename E> requires is_enum<E>::value
class flags {
public:
    flags( E value ) noexcept : m_value( to_underlying( value ) ) {}

    flags operator|( const E value ) noexcept {
        m_value |= to_underlying( value );
    }

    flags & operator|=( const E value ) noexcept {
        m_value |= to_underlying( value );
        return *this;
    }

    flags & operator=( const E value ) noexcept {
        m_value = to_underlying( value );
    }

    template<E FLAG>
    bool is_set( void ) noexcept {
        return ( m_value & to_underlying( FLAG ) );
    }

private:
    /* Abstracted type to store 'combined' value */
    typename underlying_type<E>::type m_value;
};

template<typename E> requires is_enum<E>::value
flags<E> operator|( E lhs, E rhs ) noexcept {
    return ( flags( lhs ) | rhs );
}

和一些示例标志:

enum class mode { MODE_0 = 1, MODE_1 = 2, MODE_2 = 4 };

最后像这样使用它:

template<mode... MODES>
struct user {
   void apply( flags<mode> m = MODES | ... ) {} // <- this does not work
};

user<mode::MODE_0, mode::MODE_2> sample; 

使用 void apply( flags<mode> m ),其中 m 包含内部 m_value 等于 mode::MODE0 | mode::MODE2 ( m_value == 5 )

所以问题是:

目标是获取包含特定 modes 的可变参数包,将它们与 operator| 组合以创建单个 flags<mode> 实例...

那么如何修复这条线以使其正常工作?

void apply( flags<mode> m = MODES | ... ) {} // <- this does not work

您对 fold expression 的语法不正确;折叠表达式需要放在括号中:

void apply( flags<mode> m = ( MODES | ... ) ) {}
                         // ^_____________^