[英]Using a strong enum (C++11) of type bool fails for template bool argument, why?
enum class test : bool { yes=true, no=false };
template< bool ok >
class A {
};
int main(){
A<test::yes> a;
}
為什么編譯失敗? (g++ 4.7) 由於 C++11 枚舉是強類型的,所以我們應該能夠使用 bool 枚舉作為模板類型的 bool 參數嗎?
強類型枚舉意味着您只能隱式比較和分配同一枚舉類中的值。 解決方案是使用非強類型的枚舉示例:
enum test : bool
{
yes = true,
no = false
};
bool x = test::yes; // ok
或湯姆·克納彭(Tom Knapen)的建議:明確地投射枚舉
enum class test : bool
{
yes = true,
no = false
};
bool x = static_cast<bool>(test::yes); // ok
您可以使用模板使演員表更簡單:-
enum class Test: bool {
No = false,
Yes = true
};
template <typename E>
constexpr auto operator+(E e) noexcept {
return static_cast<std::underlying_type_t<E>>(e);
}
template <typename E, std::enable_if_t<
std::is_same<bool, std::underlying_type_t<E>>::value,
int
> = 0
>
constexpr E operator not (E e) noexcept {
return static_cast<E>(!static_cast<bool>(e));
}
// then
bool x {+Test::Yes};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.