简体   繁体   中英

std::pair() having empty values with something like boost::optional

class LinkStats{
public:
    LinkStats(std::shared_ptr<Configuration> config) {
        m_interface = "eth0";
    };

    ~LinkStats() = default;

    std::pair<int32_t, int32_t> getRxLinkStats() {
        auto status = getLinkStats();
        if(nullptr != status){
            return std::make_pair(status->rx_errors, status->rx_dropped);
        }
    }

    std::pair<int32_t, int32_t> getTxLinkStats(){
        auto status = getLinkStats();
        if(nullptr != status){
            return std::make_pair(status->tx_errors, status->tx_dropped);
        }
    }

private:
    rtnl_link_stats* getLinkStats() {
        getifaddrs(&m_ifaddr);
        m_interfaceAddresses = { m_ifaddr, []( ifaddrs * x ) { freeifaddrs( x );}};
        for ( ifaddrs *ifa = m_interfaceAddresses.get(); ifa; ifa = ifa->ifa_next) {
            if ((ifa->ifa_addr->sa_family == AF_PACKET) &&
                (ifa->ifa_data != NULL) &&
                (ifa->ifa_addr != NULL) &&
                (0 == m_interface.compare(ifa->ifa_name))) {

                return static_cast<rtnl_link_stats*>(ifa->ifa_data);
            }
        }
        return nullptr;
    }

    std::unique_ptr<ifaddrs, std::function<void(ifaddrs*)>> m_interfaceAddresses;
    ifaddrs *m_ifaddr;
    std::string m_interface;
};

I have written the above class to get the link stats, rx_error , rx_dropped , tx_error , tx_dropped .

In the two functions above, getRxLinkStats() and getTxLinkStats() , I want to know if there is a elegant way to return the std::pair() that will indicate that it is empty, meaning getLinkStats() have failed.

std::optional<std::pair<int32_t, int32_t>> getRxLinkStats() {
    if (auto status = getLinkStats())
        return std::make_pair(status->rx_errors, status->rx_dropped);
    }
    return {};
}

std::optional<std::pair<int32_t, int32_t>> getTxLinkStats(){
    if (auto status = getLinkStats()) {
        return std::make_pair(status->tx_errors, status->tx_dropped);
    }
    return {};
}

for boost-based (ie, ), use boost::optional instead of std::optional .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM