【发布时间】: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<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
【问题讨论】:
-
你有什么问题?
标签: c++ enums variadic-templates c++20