enum class 使用样例

  • enum class 使用:
#pragma once

#include <vector>
#include <string>
#include <iostream>
#include <initializer_list>
using namespace std;

enum class Gender
{
    male,
    female

};


enum class altitude : char {
    high = 'h',
    low = 'l',
};

// std::ostream& operator << (std::ostream& os, const Gender& obj)
// {
//    os << static_cast<std::underlying_type<Gender>::type>(obj);
//    return os;
// }

// template<typename T>
// std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& os, const T& e)
// {
//     return os << static_cast<typename std::underlying_type<T>::type>(e);
// }

// template <typename T>
// typename std::enable_if<std::is_enum<T>::value, std::ostream>::type&
// operator<<(std::ostream& os, const T& e) {
//     return os << static_cast<typename std::underlying_type<T>::type>(e);
// }

template <typename T>
__enable_if_t<std::is_enum<T>::value, std::ostream>&
operator<<(std::ostream& os, const T& e) {
    return os << static_cast<typename std::underlying_type<T>::type>(e);
}


class People
{
private:
    vector<pair<string, Gender>> data;

public:
    People(initializer_list<pair<string, Gender>> il)  {
        for(auto i=il.begin(); i!=il.end(); ++i) {
            data.push_back(*i);
        }
    }

    void Print() {
        for (auto v: data) {            
            cout << v.first << "," << v.second << endl;
        }

    }
};

void test() {
    People p1 = {{"Tom", Gender::male}, {"Lucy", Gender::female}};
    p1.Print();

    altitude a = altitude::high;
    cout << a << endl;
}

posted @ 2025-05-21 17:47  codetodo  阅读(14)  评论(0)    收藏  举报