简体   繁体   English

在枚举类上使用std :: get时需要static_cast

[英]static_cast required when using std::get with enum class

According to the c++ reference , the template parameter of std::get is a std::size_t . 根据c ++参考std::get的模板参数是std::size_t Why does one need an explicit cast when such a parameter is an enum class with base type std::size_t , instead of having an implicit conversion? 当这样的参数是基本类型为std::size_tenum class而不是隐式转换时,为什么需要显式转换?

See following example 请参阅以下示例

#include <tuple>

enum class labels : std::size_t { red, green, blue };

int main()
{
  std::tuple<int, int, double> a;
  // std::get<labels::red>(a) = 0;
  std::get<static_cast<std::size_t>(labels::red)>(a) = 0;
  std::get<static_cast<std::size_t>(labels::green)>(a) = 0;
  std::get<static_cast<std::size_t>(labels::blue)>(a) = 0;

  return 0;
}

Uncommenting the line gives rise to a compilation error (gcc 7.3.0) 取消注释该行会引起编译错误(gcc 7.3.0)

tuple.cpp:8:26: error: could not convert template argument ‘red’ from ‘labels’ to ‘long unsigned int’
   std::get<labels::red>(a) = 0;

That's because enum class (as opposed to simple enum ) is not implicitely convertible to numeral type. 这是因为enum class (与简单的enum相反)不能隐式转换为数字类型。 You need to explicitely cast it to obtain the numeric value, for example using static_cast<>() . 您需要显式转换它以获得数字值,例如使用static_cast<>()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用static_cast将枚举类转换为int - Cannot convert enum class to int using static_cast 如果static_cast无效值枚举类会发生什么? - What happens if you static_cast invalid value to enum class? 使用带有重载函数的std :: make_tuple时如何避免static_cast - how to avoid static_cast when using std::make_tuple with overloaded functions 什么时候是`static_cast <Base*> (的static_cast <void*> (派生))`从指向派生类的指针有效吗? - When is a `static_cast<Base*>(static_cast<void*>(derived))` from a pointer to a derived class valid? 整数到枚举转换的static_cast - static_cast on integer to enum conversion std :: list static_cast派生的迭代器 - std::list static_cast derived iterator std :: bind()中static_cast的仿函数版本 - Functor version of static_cast in std::bind() 将派生对象中的“this”指针的static_cast用于基类的问题 - Question of using static_cast on “this” pointer in a derived object to base class 任何获得 static_cast 警告的方法<some_enum_class> (T) T 的类型不是 some_enum_class 的基础类型?</some_enum_class> - Any way to get a warning for static_cast<some_enum_class>(T) where T's type isn't the underlying type of some_enum_class? 访问存储在向量中的已知派生类对象时,使用dynamic_cast或static_cast有什么问题 <base*> ? - What's wrong with using dynamic_cast or static_cast when accessing known derived class objects stored in vector<base*>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM