且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std::get 使用枚举类作为模板参数

更新时间:2023-11-12 22:13:40

C++11 引入的强类型枚举不能隐式转换为 int 类型的整数值,而 std::get 期望模板参数是整型.

The strongly-typed enums introduced by C++11 cannot be implicitly converted into integral values of type say int, while std::get expects the template argument to be integral type.

您必须使用 static_cast 来转换枚举值:

You've to use static_cast to convert the enum values:

std::cout <<std::get<static_cast<int>(Bad::BAD)>(tup)<< std::endl; //Ok now!

或者您可以选择转换为底层整数类型为:

Or you can choose to convert into underlying integral type as:

//note that it is constexpr function
template <typename T>
constexpr typename std::underlying_type<T>::type integral(T value) 
{
    return static_cast<typename std::underlying_type<T>::type>(value);
}

然后将其用作:

std::cout <<std::get<integral(Bad::BAD)>(tup)<< std::endl; //Ok now!