【问题标题】:enum class varidic parameter pack to expand with binary operator枚举类可变参数包用二元运算符扩展
【发布时间】:2021-06-08 04:12:24
【问题描述】:

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

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&lt;mode&gt; m ),其中m 包含内部m_value 等于mode::MODE0 | mode::MODE2 (m_value == 5)

所以问题是:

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

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

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

【问题讨论】:

  • 你有什么问题?

标签: c++ enums variadic-templates c++20


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多