mercredi 25 mars 2020

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.

Aucun commentaire:

Enregistrer un commentaire