[英]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_t
的enum 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.