Modeling an IP AddressDynamic IP-address loggingValidate IP address in JavaArray-like container for uints shorter than 8 bits (Rev 1)Identifying originating country of an IP addressCalculate IP AddressRegex to check IP address in JavaPattern for writing a generic string transformation functionRandom IP Address GeneratorModeling a parking lotValidate IP4 address

How do conventional missiles fly?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Is it inappropriate for a student to attend their mentor's dissertation defense?

In a Spin are Both Wings Stalled?

Why can't we play rap on piano?

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

Why does Arabsat 6A need a Falcon Heavy to launch

Modeling an IP Address

A reference to a well-known characterization of scattered compact spaces

Where does SFDX store details about scratch orgs?

Would Slavery Reparations be considered Bills of Attainder and hence Illegal?

Python: return float 1.0 as int 1 but float 1.5 as float 1.5

What is the most common color to indicate the input-field is disabled?

How is it possible to have an ability score that is less than 3?

How to prevent "they're falling in love" trope

Why is Collection not simply treated as Collection<?>

Took a trip to a parallel universe, need help deciphering

Forgetting the musical notes while performing in concert

Were any external disk drives stacked vertically?

Theorems that impeded progress

Assassin's bullet with mercury

In Romance of the Three Kingdoms why do people still use bamboo sticks when papers are already invented?

Stopping power of mountain vs road bike

Why does Kotter return in Welcome Back Kotter



Modeling an IP Address


Dynamic IP-address loggingValidate IP address in JavaArray-like container for uints shorter than 8 bits (Rev 1)Identifying originating country of an IP addressCalculate IP AddressRegex to check IP address in JavaPattern for writing a generic string transformation functionRandom IP Address GeneratorModeling a parking lotValidate IP4 address






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3












$begingroup$


I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on Github. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features I'm not taking advantage of.



ip_address.h



#pragma once

#include <array>
#include <string>
#include <string_view>
#include <stdint.h>

namespace ip

/**
* @brief Thrown when there is an invalid ip address passed via
* string.
*/
class invalid_format_exception : public std::exception

std::string invalid_format_;
public:
invalid_format_exception(const std::string &invalid_format);
char const* what() const override;
;

/**
* Class that models a IPv4 address.
*/
class address

public:

#pragma region Type definitions
using value_type = uint8_t;
using reference = value_type & ;
using pointer = value_type * ;
using iterator = std::array<value_type, 4>::iterator;
using const_iterator = std::array<value_type, 4>::const_iterator;
using reverse_iterator = std::array<value_type, 4>::reverse_iterator;
using const_reverse_iterator = std::array<value_type, 4>::const_reverse_iterator;
using size_type = std::array<value_type, 4>::size_type;
#pragma endregion

/**
* @brief Create an IP address representation from the
* four parts of the address definition.
* @param first the first part of the address
* @param second the second part of the address
* @param third the third part of the address.
* @param fourth the fourth part of the address.
* @details Example:
* @code
* ip::address addr(127, 0, 0, 1);
* @endcode
*/
address(const value_type& first, const value_type &second,
const value_type &third, const value_type& fourth);

/**
* @brief Create an IP address representaiton from an
* array.
* @param data the data array.
* @details Example:
* @code
* ip::address addr = 127, 0, 0, 1;
* @endcode
*/
address(const std::array<unsigned char, 4> &data);

/**
* @brief Create an IP adderss representation from a
* unsigned 32 bit integer.
* @param value the integer representation of an IP address.
*/
explicit address(const uint32_t &value);

/**
* @brief Implicit conversion to an unsigned 32 bit integer.
*/
uint32_t operator()() const;

/**
* @brief Access operator.
* @param index the index to access.
*/
reference operator[](const int &index) noexcept(false);

/**
* @brief Const version of the access operator.
*/
value_type operator[](const int &index) const noexcept(false);

/**
* @brief Prefix increment operator.
*/
void operator++();

/**
* @brief Postfix increment operator.
*/
::ip::address& operator++(int);

/**
* @brief Prefix decrement operator.
*/
void operator--();

/**
* @brief Prefix decrement operator.
*/
::ip::address& operator--(int);

iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
private:
std::array<value_type, 4> data_;
;

bool operator<(const ip::address &first, const ip::address &second);
bool operator==(const ip::address &first, const ip::address &second);
std::ostream& operator<<(std::ostream& output, const ip::address &address);
address from_string(const std::string &view);
std::string to_string(const address& address);



ip_address.cpp



#include <ip_address.h>

#include <iterator>
#include <iostream>
#include <sstream>
#include <regex>
#include <vector>
#include <string>

#pragma region Utilities
template<typename Output>
void split(const std::string &s, char delim, Output result)
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
*(result++) = item;



std::vector<std::string> split(const std::string &s, char delim)
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;


#pragma endregion

ip::invalid_format_exception::invalid_format_exception(const std::string& invalid_format)
: invalid_format_(invalid_format)



char const* ip::invalid_format_exception::what() const

std::ostringstream oss;
oss << "Invalid IP address format: " << invalid_format_;
return oss.str().c_str();


ip::address::address(const value_type & first, const value_type & second, const value_type & third, const value_type & fourth)

data_[0] = first;
data_[1] = second;
data_[2] = third;
data_[3] = fourth;


ip::address::address(const std::array<unsigned char, 4>& data)

data_ = data;


ip::address::address(const uint32_t& value)

data_[0] = value >> 24 & 0xFF;
data_[1] = value >> 16 & 0xFF;
data_[2] = value >> 8 & 0xFF;
data_[3] = value & 0xFF;


uint32_t ip::address::operator()() const

const uint32_t value = data_[0] << 24

ip::address::reference ip::address::operator[](const int& index)

return data_.at(index);


ip::address::value_type ip::address::operator[](const int& index) const

return data_.at(index);


void ip::address::operator++()

auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

return data < 255;
);

if(location != std::rend(data_))

const auto r_index = std::distance(data_.rbegin(), location);
auto index = 4 - r_index - 1;
data_[index]++;



::ip::address& ip::address::operator++(int)

auto result(*this);
++(*this);
return result;


void ip::address::operator--()

auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

return data < 255;
);

if (location != std::rend(data_))

const auto r_index = std::distance(data_.rbegin(), location);
auto index = 4 - r_index - 1;
data_[index]--;



::ip::address& ip::address::operator--(int)

auto result(*this);
--(*this);
return result;


ip::address::iterator ip::address::begin()

return data_.begin();


ip::address::const_iterator ip::address::end() const

return data_.end();


bool ip::operator<(const ip::address& first, const ip::address& second)

return (uint32_t)first() < (uint32_t)second();


bool ip::operator==(const ip::address& first, const ip::address& second)

return (uint32_t)first() == (uint32_t) second();


ip::address::const_iterator ip::address::begin() const

return data_.begin();


ip::address::iterator ip::address::end()

return data_.end();


std::ostream& ip::operator<<(std::ostream& output, const ip::address& address)

std::copy(address.begin(), address.end()-1,
std::ostream_iterator<short>(output, "."));
output << +address[3];
return output;


ip::address ip::from_string(const std::string &view)

auto parts = split(view, '.');
if (parts.size() != 4)

throw invalid_format_exception(view);


return
(ip::address::value_type)std::stoi(parts[0]),
(ip::address::value_type)std::stoi(parts[1]),
(ip::address::value_type)std::stoi(parts[2]),
(ip::address::value_type)std::stoi(parts[3])
;


std::string ip::to_string(const address& address)

std::ostringstream string_stream;
string_stream << address;
return string_stream.str();










share|improve this question







New contributor




Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    3












    $begingroup$


    I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on Github. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features I'm not taking advantage of.



    ip_address.h



    #pragma once

    #include <array>
    #include <string>
    #include <string_view>
    #include <stdint.h>

    namespace ip

    /**
    * @brief Thrown when there is an invalid ip address passed via
    * string.
    */
    class invalid_format_exception : public std::exception

    std::string invalid_format_;
    public:
    invalid_format_exception(const std::string &invalid_format);
    char const* what() const override;
    ;

    /**
    * Class that models a IPv4 address.
    */
    class address

    public:

    #pragma region Type definitions
    using value_type = uint8_t;
    using reference = value_type & ;
    using pointer = value_type * ;
    using iterator = std::array<value_type, 4>::iterator;
    using const_iterator = std::array<value_type, 4>::const_iterator;
    using reverse_iterator = std::array<value_type, 4>::reverse_iterator;
    using const_reverse_iterator = std::array<value_type, 4>::const_reverse_iterator;
    using size_type = std::array<value_type, 4>::size_type;
    #pragma endregion

    /**
    * @brief Create an IP address representation from the
    * four parts of the address definition.
    * @param first the first part of the address
    * @param second the second part of the address
    * @param third the third part of the address.
    * @param fourth the fourth part of the address.
    * @details Example:
    * @code
    * ip::address addr(127, 0, 0, 1);
    * @endcode
    */
    address(const value_type& first, const value_type &second,
    const value_type &third, const value_type& fourth);

    /**
    * @brief Create an IP address representaiton from an
    * array.
    * @param data the data array.
    * @details Example:
    * @code
    * ip::address addr = 127, 0, 0, 1;
    * @endcode
    */
    address(const std::array<unsigned char, 4> &data);

    /**
    * @brief Create an IP adderss representation from a
    * unsigned 32 bit integer.
    * @param value the integer representation of an IP address.
    */
    explicit address(const uint32_t &value);

    /**
    * @brief Implicit conversion to an unsigned 32 bit integer.
    */
    uint32_t operator()() const;

    /**
    * @brief Access operator.
    * @param index the index to access.
    */
    reference operator[](const int &index) noexcept(false);

    /**
    * @brief Const version of the access operator.
    */
    value_type operator[](const int &index) const noexcept(false);

    /**
    * @brief Prefix increment operator.
    */
    void operator++();

    /**
    * @brief Postfix increment operator.
    */
    ::ip::address& operator++(int);

    /**
    * @brief Prefix decrement operator.
    */
    void operator--();

    /**
    * @brief Prefix decrement operator.
    */
    ::ip::address& operator--(int);

    iterator begin();
    iterator end();
    const_iterator begin() const;
    const_iterator end() const;
    private:
    std::array<value_type, 4> data_;
    ;

    bool operator<(const ip::address &first, const ip::address &second);
    bool operator==(const ip::address &first, const ip::address &second);
    std::ostream& operator<<(std::ostream& output, const ip::address &address);
    address from_string(const std::string &view);
    std::string to_string(const address& address);



    ip_address.cpp



    #include <ip_address.h>

    #include <iterator>
    #include <iostream>
    #include <sstream>
    #include <regex>
    #include <vector>
    #include <string>

    #pragma region Utilities
    template<typename Output>
    void split(const std::string &s, char delim, Output result)
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    *(result++) = item;



    std::vector<std::string> split(const std::string &s, char delim)
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;


    #pragma endregion

    ip::invalid_format_exception::invalid_format_exception(const std::string& invalid_format)
    : invalid_format_(invalid_format)



    char const* ip::invalid_format_exception::what() const

    std::ostringstream oss;
    oss << "Invalid IP address format: " << invalid_format_;
    return oss.str().c_str();


    ip::address::address(const value_type & first, const value_type & second, const value_type & third, const value_type & fourth)

    data_[0] = first;
    data_[1] = second;
    data_[2] = third;
    data_[3] = fourth;


    ip::address::address(const std::array<unsigned char, 4>& data)

    data_ = data;


    ip::address::address(const uint32_t& value)

    data_[0] = value >> 24 & 0xFF;
    data_[1] = value >> 16 & 0xFF;
    data_[2] = value >> 8 & 0xFF;
    data_[3] = value & 0xFF;


    uint32_t ip::address::operator()() const

    const uint32_t value = data_[0] << 24

    ip::address::reference ip::address::operator[](const int& index)

    return data_.at(index);


    ip::address::value_type ip::address::operator[](const int& index) const

    return data_.at(index);


    void ip::address::operator++()

    auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

    return data < 255;
    );

    if(location != std::rend(data_))

    const auto r_index = std::distance(data_.rbegin(), location);
    auto index = 4 - r_index - 1;
    data_[index]++;



    ::ip::address& ip::address::operator++(int)

    auto result(*this);
    ++(*this);
    return result;


    void ip::address::operator--()

    auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

    return data < 255;
    );

    if (location != std::rend(data_))

    const auto r_index = std::distance(data_.rbegin(), location);
    auto index = 4 - r_index - 1;
    data_[index]--;



    ::ip::address& ip::address::operator--(int)

    auto result(*this);
    --(*this);
    return result;


    ip::address::iterator ip::address::begin()

    return data_.begin();


    ip::address::const_iterator ip::address::end() const

    return data_.end();


    bool ip::operator<(const ip::address& first, const ip::address& second)

    return (uint32_t)first() < (uint32_t)second();


    bool ip::operator==(const ip::address& first, const ip::address& second)

    return (uint32_t)first() == (uint32_t) second();


    ip::address::const_iterator ip::address::begin() const

    return data_.begin();


    ip::address::iterator ip::address::end()

    return data_.end();


    std::ostream& ip::operator<<(std::ostream& output, const ip::address& address)

    std::copy(address.begin(), address.end()-1,
    std::ostream_iterator<short>(output, "."));
    output << +address[3];
    return output;


    ip::address ip::from_string(const std::string &view)

    auto parts = split(view, '.');
    if (parts.size() != 4)

    throw invalid_format_exception(view);


    return
    (ip::address::value_type)std::stoi(parts[0]),
    (ip::address::value_type)std::stoi(parts[1]),
    (ip::address::value_type)std::stoi(parts[2]),
    (ip::address::value_type)std::stoi(parts[3])
    ;


    std::string ip::to_string(const address& address)

    std::ostringstream string_stream;
    string_stream << address;
    return string_stream.str();










    share|improve this question







    New contributor




    Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      3












      3








      3





      $begingroup$


      I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on Github. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features I'm not taking advantage of.



      ip_address.h



      #pragma once

      #include <array>
      #include <string>
      #include <string_view>
      #include <stdint.h>

      namespace ip

      /**
      * @brief Thrown when there is an invalid ip address passed via
      * string.
      */
      class invalid_format_exception : public std::exception

      std::string invalid_format_;
      public:
      invalid_format_exception(const std::string &invalid_format);
      char const* what() const override;
      ;

      /**
      * Class that models a IPv4 address.
      */
      class address

      public:

      #pragma region Type definitions
      using value_type = uint8_t;
      using reference = value_type & ;
      using pointer = value_type * ;
      using iterator = std::array<value_type, 4>::iterator;
      using const_iterator = std::array<value_type, 4>::const_iterator;
      using reverse_iterator = std::array<value_type, 4>::reverse_iterator;
      using const_reverse_iterator = std::array<value_type, 4>::const_reverse_iterator;
      using size_type = std::array<value_type, 4>::size_type;
      #pragma endregion

      /**
      * @brief Create an IP address representation from the
      * four parts of the address definition.
      * @param first the first part of the address
      * @param second the second part of the address
      * @param third the third part of the address.
      * @param fourth the fourth part of the address.
      * @details Example:
      * @code
      * ip::address addr(127, 0, 0, 1);
      * @endcode
      */
      address(const value_type& first, const value_type &second,
      const value_type &third, const value_type& fourth);

      /**
      * @brief Create an IP address representaiton from an
      * array.
      * @param data the data array.
      * @details Example:
      * @code
      * ip::address addr = 127, 0, 0, 1;
      * @endcode
      */
      address(const std::array<unsigned char, 4> &data);

      /**
      * @brief Create an IP adderss representation from a
      * unsigned 32 bit integer.
      * @param value the integer representation of an IP address.
      */
      explicit address(const uint32_t &value);

      /**
      * @brief Implicit conversion to an unsigned 32 bit integer.
      */
      uint32_t operator()() const;

      /**
      * @brief Access operator.
      * @param index the index to access.
      */
      reference operator[](const int &index) noexcept(false);

      /**
      * @brief Const version of the access operator.
      */
      value_type operator[](const int &index) const noexcept(false);

      /**
      * @brief Prefix increment operator.
      */
      void operator++();

      /**
      * @brief Postfix increment operator.
      */
      ::ip::address& operator++(int);

      /**
      * @brief Prefix decrement operator.
      */
      void operator--();

      /**
      * @brief Prefix decrement operator.
      */
      ::ip::address& operator--(int);

      iterator begin();
      iterator end();
      const_iterator begin() const;
      const_iterator end() const;
      private:
      std::array<value_type, 4> data_;
      ;

      bool operator<(const ip::address &first, const ip::address &second);
      bool operator==(const ip::address &first, const ip::address &second);
      std::ostream& operator<<(std::ostream& output, const ip::address &address);
      address from_string(const std::string &view);
      std::string to_string(const address& address);



      ip_address.cpp



      #include <ip_address.h>

      #include <iterator>
      #include <iostream>
      #include <sstream>
      #include <regex>
      #include <vector>
      #include <string>

      #pragma region Utilities
      template<typename Output>
      void split(const std::string &s, char delim, Output result)
      std::stringstream ss(s);
      std::string item;
      while (std::getline(ss, item, delim))
      *(result++) = item;



      std::vector<std::string> split(const std::string &s, char delim)
      std::vector<std::string> elems;
      split(s, delim, std::back_inserter(elems));
      return elems;


      #pragma endregion

      ip::invalid_format_exception::invalid_format_exception(const std::string& invalid_format)
      : invalid_format_(invalid_format)



      char const* ip::invalid_format_exception::what() const

      std::ostringstream oss;
      oss << "Invalid IP address format: " << invalid_format_;
      return oss.str().c_str();


      ip::address::address(const value_type & first, const value_type & second, const value_type & third, const value_type & fourth)

      data_[0] = first;
      data_[1] = second;
      data_[2] = third;
      data_[3] = fourth;


      ip::address::address(const std::array<unsigned char, 4>& data)

      data_ = data;


      ip::address::address(const uint32_t& value)

      data_[0] = value >> 24 & 0xFF;
      data_[1] = value >> 16 & 0xFF;
      data_[2] = value >> 8 & 0xFF;
      data_[3] = value & 0xFF;


      uint32_t ip::address::operator()() const

      const uint32_t value = data_[0] << 24

      ip::address::reference ip::address::operator[](const int& index)

      return data_.at(index);


      ip::address::value_type ip::address::operator[](const int& index) const

      return data_.at(index);


      void ip::address::operator++()

      auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

      return data < 255;
      );

      if(location != std::rend(data_))

      const auto r_index = std::distance(data_.rbegin(), location);
      auto index = 4 - r_index - 1;
      data_[index]++;



      ::ip::address& ip::address::operator++(int)

      auto result(*this);
      ++(*this);
      return result;


      void ip::address::operator--()

      auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

      return data < 255;
      );

      if (location != std::rend(data_))

      const auto r_index = std::distance(data_.rbegin(), location);
      auto index = 4 - r_index - 1;
      data_[index]--;



      ::ip::address& ip::address::operator--(int)

      auto result(*this);
      --(*this);
      return result;


      ip::address::iterator ip::address::begin()

      return data_.begin();


      ip::address::const_iterator ip::address::end() const

      return data_.end();


      bool ip::operator<(const ip::address& first, const ip::address& second)

      return (uint32_t)first() < (uint32_t)second();


      bool ip::operator==(const ip::address& first, const ip::address& second)

      return (uint32_t)first() == (uint32_t) second();


      ip::address::const_iterator ip::address::begin() const

      return data_.begin();


      ip::address::iterator ip::address::end()

      return data_.end();


      std::ostream& ip::operator<<(std::ostream& output, const ip::address& address)

      std::copy(address.begin(), address.end()-1,
      std::ostream_iterator<short>(output, "."));
      output << +address[3];
      return output;


      ip::address ip::from_string(const std::string &view)

      auto parts = split(view, '.');
      if (parts.size() != 4)

      throw invalid_format_exception(view);


      return
      (ip::address::value_type)std::stoi(parts[0]),
      (ip::address::value_type)std::stoi(parts[1]),
      (ip::address::value_type)std::stoi(parts[2]),
      (ip::address::value_type)std::stoi(parts[3])
      ;


      std::string ip::to_string(const address& address)

      std::ostringstream string_stream;
      string_stream << address;
      return string_stream.str();










      share|improve this question







      New contributor




      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on Github. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features I'm not taking advantage of.



      ip_address.h



      #pragma once

      #include <array>
      #include <string>
      #include <string_view>
      #include <stdint.h>

      namespace ip

      /**
      * @brief Thrown when there is an invalid ip address passed via
      * string.
      */
      class invalid_format_exception : public std::exception

      std::string invalid_format_;
      public:
      invalid_format_exception(const std::string &invalid_format);
      char const* what() const override;
      ;

      /**
      * Class that models a IPv4 address.
      */
      class address

      public:

      #pragma region Type definitions
      using value_type = uint8_t;
      using reference = value_type & ;
      using pointer = value_type * ;
      using iterator = std::array<value_type, 4>::iterator;
      using const_iterator = std::array<value_type, 4>::const_iterator;
      using reverse_iterator = std::array<value_type, 4>::reverse_iterator;
      using const_reverse_iterator = std::array<value_type, 4>::const_reverse_iterator;
      using size_type = std::array<value_type, 4>::size_type;
      #pragma endregion

      /**
      * @brief Create an IP address representation from the
      * four parts of the address definition.
      * @param first the first part of the address
      * @param second the second part of the address
      * @param third the third part of the address.
      * @param fourth the fourth part of the address.
      * @details Example:
      * @code
      * ip::address addr(127, 0, 0, 1);
      * @endcode
      */
      address(const value_type& first, const value_type &second,
      const value_type &third, const value_type& fourth);

      /**
      * @brief Create an IP address representaiton from an
      * array.
      * @param data the data array.
      * @details Example:
      * @code
      * ip::address addr = 127, 0, 0, 1;
      * @endcode
      */
      address(const std::array<unsigned char, 4> &data);

      /**
      * @brief Create an IP adderss representation from a
      * unsigned 32 bit integer.
      * @param value the integer representation of an IP address.
      */
      explicit address(const uint32_t &value);

      /**
      * @brief Implicit conversion to an unsigned 32 bit integer.
      */
      uint32_t operator()() const;

      /**
      * @brief Access operator.
      * @param index the index to access.
      */
      reference operator[](const int &index) noexcept(false);

      /**
      * @brief Const version of the access operator.
      */
      value_type operator[](const int &index) const noexcept(false);

      /**
      * @brief Prefix increment operator.
      */
      void operator++();

      /**
      * @brief Postfix increment operator.
      */
      ::ip::address& operator++(int);

      /**
      * @brief Prefix decrement operator.
      */
      void operator--();

      /**
      * @brief Prefix decrement operator.
      */
      ::ip::address& operator--(int);

      iterator begin();
      iterator end();
      const_iterator begin() const;
      const_iterator end() const;
      private:
      std::array<value_type, 4> data_;
      ;

      bool operator<(const ip::address &first, const ip::address &second);
      bool operator==(const ip::address &first, const ip::address &second);
      std::ostream& operator<<(std::ostream& output, const ip::address &address);
      address from_string(const std::string &view);
      std::string to_string(const address& address);



      ip_address.cpp



      #include <ip_address.h>

      #include <iterator>
      #include <iostream>
      #include <sstream>
      #include <regex>
      #include <vector>
      #include <string>

      #pragma region Utilities
      template<typename Output>
      void split(const std::string &s, char delim, Output result)
      std::stringstream ss(s);
      std::string item;
      while (std::getline(ss, item, delim))
      *(result++) = item;



      std::vector<std::string> split(const std::string &s, char delim)
      std::vector<std::string> elems;
      split(s, delim, std::back_inserter(elems));
      return elems;


      #pragma endregion

      ip::invalid_format_exception::invalid_format_exception(const std::string& invalid_format)
      : invalid_format_(invalid_format)



      char const* ip::invalid_format_exception::what() const

      std::ostringstream oss;
      oss << "Invalid IP address format: " << invalid_format_;
      return oss.str().c_str();


      ip::address::address(const value_type & first, const value_type & second, const value_type & third, const value_type & fourth)

      data_[0] = first;
      data_[1] = second;
      data_[2] = third;
      data_[3] = fourth;


      ip::address::address(const std::array<unsigned char, 4>& data)

      data_ = data;


      ip::address::address(const uint32_t& value)

      data_[0] = value >> 24 & 0xFF;
      data_[1] = value >> 16 & 0xFF;
      data_[2] = value >> 8 & 0xFF;
      data_[3] = value & 0xFF;


      uint32_t ip::address::operator()() const

      const uint32_t value = data_[0] << 24

      ip::address::reference ip::address::operator[](const int& index)

      return data_.at(index);


      ip::address::value_type ip::address::operator[](const int& index) const

      return data_.at(index);


      void ip::address::operator++()

      auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

      return data < 255;
      );

      if(location != std::rend(data_))

      const auto r_index = std::distance(data_.rbegin(), location);
      auto index = 4 - r_index - 1;
      data_[index]++;



      ::ip::address& ip::address::operator++(int)

      auto result(*this);
      ++(*this);
      return result;


      void ip::address::operator--()

      auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

      return data < 255;
      );

      if (location != std::rend(data_))

      const auto r_index = std::distance(data_.rbegin(), location);
      auto index = 4 - r_index - 1;
      data_[index]--;



      ::ip::address& ip::address::operator--(int)

      auto result(*this);
      --(*this);
      return result;


      ip::address::iterator ip::address::begin()

      return data_.begin();


      ip::address::const_iterator ip::address::end() const

      return data_.end();


      bool ip::operator<(const ip::address& first, const ip::address& second)

      return (uint32_t)first() < (uint32_t)second();


      bool ip::operator==(const ip::address& first, const ip::address& second)

      return (uint32_t)first() == (uint32_t) second();


      ip::address::const_iterator ip::address::begin() const

      return data_.begin();


      ip::address::iterator ip::address::end()

      return data_.end();


      std::ostream& ip::operator<<(std::ostream& output, const ip::address& address)

      std::copy(address.begin(), address.end()-1,
      std::ostream_iterator<short>(output, "."));
      output << +address[3];
      return output;


      ip::address ip::from_string(const std::string &view)

      auto parts = split(view, '.');
      if (parts.size() != 4)

      throw invalid_format_exception(view);


      return
      (ip::address::value_type)std::stoi(parts[0]),
      (ip::address::value_type)std::stoi(parts[1]),
      (ip::address::value_type)std::stoi(parts[2]),
      (ip::address::value_type)std::stoi(parts[3])
      ;


      std::string ip::to_string(const address& address)

      std::ostringstream string_stream;
      string_stream << address;
      return string_stream.str();







      c++ c++11 ip-address






      share|improve this question







      New contributor




      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 3 hours ago









      Developer PaulDeveloper Paul

      1162




      1162




      New contributor




      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Developer Paul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          3 Answers
          3






          active

          oldest

          votes


















          1












          $begingroup$

          You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like



          explicit address(uint32_t value);
          reference operator[](int index) noexcept(false);


          Your prefix increment and decrement operators should return a reference to the incremented value.



          address &operator++() /* ... */ return *this; 
          address &operator--() /* ... */ return *this;


          This will allow expressions like addr = ++other_addr;. (Note that, since you're in the address class, you can just name the class, you don't need to specify scope with ::ip::address).



          Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.



          address operator++(int);
          address operator--(int);


          For readability and clarity, expressions mixing shifts and bit masking should use parentheses:



          data_[0] = (value >> 24) & 0xFF;





          share|improve this answer











          $endgroup$




















            1












            $begingroup$

            You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.



             using Storage = std::array<value_type, 4>;
            using iterator = Storage::iterator;
            using const_iterator = Storage::const_iterator;
            using reverse_iterator = Storage::reverse_iterator;
            using const_reverse_iterator = Storage::const_reverse_iterator;
            using size_type = Storage::size_type;


            Now if you change the underlying storage type you only have to change it in one place.




            What does it mean to increment/decrement an ip address?



             /**
            * @brief Prefix increment operator.
            */
            void operator++();


            What scenario does this make sense?




            If there is a test for equality:



            bool operator==(const ip::address &first, const ip::address &second);


            Then I would expect a test for inequality.




            If there is an output operator:



            std::ostream& operator<<(std::ostream& output, const ip::address &address);


            Then I would expect an input operator.




            The standard exceptions (except std::exception itself) already implement what(). You should inherit from one of these rather than std::exception (probably std::runtime_error.



            class invalid_format_exception : public std::exception

            std::string invalid_format_;
            public:
            invalid_format_exception(const std::string &invalid_format);
            char const* what() const override;
            ;


            This becomes:



            struct invalid_format_exception: std::runtime_error

            using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.
            ;



            Are you sure that the IP address is always stored in big endian form?



            data_[0] = value >> 24 & 0xFF;
            data_[1] = value >> 16 & 0xFF;
            data_[2] = value >> 8 & 0xFF;
            data_[3] = value & 0xFF;


            I would double check and also add a big comment that that is what you expect.




            The increment operator looks complicated.

            I think it can really be simplified by using some existing functions you have identified.



            void ip::address::operator++()

            uint32_t value = (*this); // convert to 32 bit number
            ++value; // Add 1
            (*this) = address(value); // convert back to address and copy/move




            Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:



            ip::address::iterator ip::address::begin()

            return data_.begin();


            ip::address::const_iterator ip::address::end() const

            return data_.end();


            // I would just do the following the header:


            iterator begin() return data_.begin();
            iterator end() return data_.end();
            const_iterator begin() const return data_.begin();
            const_iterator end() const return data_.end();


            You are of course missing a few:



             const_iterator cbegin() const return data_.cbegin();
            reverse_iterator rbegin() return data_.rbegin();

            // You can add the end() versions.





            share|improve this answer









            $endgroup$




















              1












              $begingroup$

              I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a range of octets. What benefit do you gain from that? IMHO: none. None benefit.




              As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:



              ::ip::address& ip::address::operator++(int)

              auto result(*this);
              ++(*this);
              return result;



              This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to compile with -W -Wall -Wextra and fix all the warnings prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!




              ip::address::iterator ip::address::begin()

              return data_.begin();


              ip::address::const_iterator ip::address::end() const

              return data_.end();



              It is super weird to me that you define these member functions in the order "nonconst begin, const end, const begin, nonconst end." That's harmless, but it's just weird. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:



               iterator begin() return data_.begin(); 
              iterator end() return data_.end();
              const_iterator begin() const return data_.begin();
              const_iterator end() const return data_.end();
              private:
              std::array<value_type, 4> data_;


              Also, all four of these methods should probably be declared noexcept.




              Overloaded comparison operators should always be defined in-line in the body of the class, using the "hidden friend" (a.k.a. "ADL friend," a.k.a. "Barton-Nackman") trick. That is, instead of



              class address ... ;

              bool operator<(const ip::address &first, const ip::address &second);

              bool ip::operator<(const ip::address& first, const ip::address& second)

              return (uint32_t)first() < (uint32_t)second();



              you should write simply



              class address 
              // ...

              friend bool operator<(const address& a, const address& b)
              return uint32_t(a()) < uint32_t(b());

              ;


              Notice that I switched your type-casts from C style to constructor-style, a.k.a. "Python style," just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose first and second to simply a and b: we don't need long names for these extremely locally scoped variables.



              But wait, there's more! I initially assumed that first() was a typo — but it's not! You actually declared an overloaded operator():



               /**
              * @brief Implicit conversion to an unsigned 32 bit integer.
              */
              uint32_t operator()() const;


              Why on earth is this an overloaded function-call operator instead of a conversion operator? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function ip::to_string(const address&)? Why is the conversion to uint32_t not implemented as ip::to_uint32(const address&)?



              Consistency is important. Also, compatibility with the rest of the language is important. When you overload operator(), you're making ip::address "callable," which means you're enabling your clients to write things like



              ip::address myAddress(127, 0, 0, 1);
              std::function<int()> f = myAddress; // !!
              assert(f() == 0x7F000001);


              Just as with the iterator/range-of-octets business, this functionality strikes me as fundamentally not what an IP address ought to be about. IP addresses aren't ranges, and IP addresses aren't callables. They should be just addresses. To the extent that your ip::address is anything other than just an address, you have actually failed in your stated goal of "modeling an IP address"!




              Your operator<< should also be defined in-line.



              Anytime you provide operator==, you should also provide operator!= — the language doesn't (yet) provide it for you automatically.



              Anytime you provide operator<, you should also provide operator<=, >, and >= — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have operator<=> to play with!)




              void ip::address::operator++()

              auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

              return data < 255;
              );

              if(location != std::rend(data_))

              const auto r_index = std::distance(data_.rbegin(), location);
              auto index = 4 - r_index - 1;
              data_[index]++;




              It's odd that you write data_.rend() in one place and std::rend(data_) in the other. I recommend the former in both cases, simply because it's shorter.



              However, doesn't this code "increment" address(0, 0, 0, 255) to address(0, 0, 1, 255) instead of to address(0, 0, 1, 0)? If so, oops! IMO the clearest and simplest way to write this "odometer algorithm" is simply



              address& operator++() noexcept

              if (++data_[3] == 0)
              if (++data_[2] == 0)
              if (++data_[1] == 0)
              ++data_[0];



              return *this;



              Short and sweet. Arguably it's overly complicated and "clever" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines longer, and (AFAICT) doesn't even work. So feel free to reduce the "cleverness" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.






              share|improve this answer









              $endgroup$













                Your Answer





                StackExchange.ifUsing("editor", function ()
                return StackExchange.using("mathjaxEditing", function ()
                StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
                StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                );
                );
                , "mathjax-editing");

                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "196"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );






                Developer Paul is a new contributor. Be nice, and check out our Code of Conduct.









                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216894%2fmodeling-an-ip-address%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1












                $begingroup$

                You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like



                explicit address(uint32_t value);
                reference operator[](int index) noexcept(false);


                Your prefix increment and decrement operators should return a reference to the incremented value.



                address &operator++() /* ... */ return *this; 
                address &operator--() /* ... */ return *this;


                This will allow expressions like addr = ++other_addr;. (Note that, since you're in the address class, you can just name the class, you don't need to specify scope with ::ip::address).



                Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.



                address operator++(int);
                address operator--(int);


                For readability and clarity, expressions mixing shifts and bit masking should use parentheses:



                data_[0] = (value >> 24) & 0xFF;





                share|improve this answer











                $endgroup$

















                  1












                  $begingroup$

                  You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like



                  explicit address(uint32_t value);
                  reference operator[](int index) noexcept(false);


                  Your prefix increment and decrement operators should return a reference to the incremented value.



                  address &operator++() /* ... */ return *this; 
                  address &operator--() /* ... */ return *this;


                  This will allow expressions like addr = ++other_addr;. (Note that, since you're in the address class, you can just name the class, you don't need to specify scope with ::ip::address).



                  Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.



                  address operator++(int);
                  address operator--(int);


                  For readability and clarity, expressions mixing shifts and bit masking should use parentheses:



                  data_[0] = (value >> 24) & 0xFF;





                  share|improve this answer











                  $endgroup$















                    1












                    1








                    1





                    $begingroup$

                    You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like



                    explicit address(uint32_t value);
                    reference operator[](int index) noexcept(false);


                    Your prefix increment and decrement operators should return a reference to the incremented value.



                    address &operator++() /* ... */ return *this; 
                    address &operator--() /* ... */ return *this;


                    This will allow expressions like addr = ++other_addr;. (Note that, since you're in the address class, you can just name the class, you don't need to specify scope with ::ip::address).



                    Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.



                    address operator++(int);
                    address operator--(int);


                    For readability and clarity, expressions mixing shifts and bit masking should use parentheses:



                    data_[0] = (value >> 24) & 0xFF;





                    share|improve this answer











                    $endgroup$



                    You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like



                    explicit address(uint32_t value);
                    reference operator[](int index) noexcept(false);


                    Your prefix increment and decrement operators should return a reference to the incremented value.



                    address &operator++() /* ... */ return *this; 
                    address &operator--() /* ... */ return *this;


                    This will allow expressions like addr = ++other_addr;. (Note that, since you're in the address class, you can just name the class, you don't need to specify scope with ::ip::address).



                    Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.



                    address operator++(int);
                    address operator--(int);


                    For readability and clarity, expressions mixing shifts and bit masking should use parentheses:



                    data_[0] = (value >> 24) & 0xFF;






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 1 hour ago

























                    answered 2 hours ago









                    1201ProgramAlarm1201ProgramAlarm

                    3,6032925




                    3,6032925























                        1












                        $begingroup$

                        You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.



                         using Storage = std::array<value_type, 4>;
                        using iterator = Storage::iterator;
                        using const_iterator = Storage::const_iterator;
                        using reverse_iterator = Storage::reverse_iterator;
                        using const_reverse_iterator = Storage::const_reverse_iterator;
                        using size_type = Storage::size_type;


                        Now if you change the underlying storage type you only have to change it in one place.




                        What does it mean to increment/decrement an ip address?



                         /**
                        * @brief Prefix increment operator.
                        */
                        void operator++();


                        What scenario does this make sense?




                        If there is a test for equality:



                        bool operator==(const ip::address &first, const ip::address &second);


                        Then I would expect a test for inequality.




                        If there is an output operator:



                        std::ostream& operator<<(std::ostream& output, const ip::address &address);


                        Then I would expect an input operator.




                        The standard exceptions (except std::exception itself) already implement what(). You should inherit from one of these rather than std::exception (probably std::runtime_error.



                        class invalid_format_exception : public std::exception

                        std::string invalid_format_;
                        public:
                        invalid_format_exception(const std::string &invalid_format);
                        char const* what() const override;
                        ;


                        This becomes:



                        struct invalid_format_exception: std::runtime_error

                        using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.
                        ;



                        Are you sure that the IP address is always stored in big endian form?



                        data_[0] = value >> 24 & 0xFF;
                        data_[1] = value >> 16 & 0xFF;
                        data_[2] = value >> 8 & 0xFF;
                        data_[3] = value & 0xFF;


                        I would double check and also add a big comment that that is what you expect.




                        The increment operator looks complicated.

                        I think it can really be simplified by using some existing functions you have identified.



                        void ip::address::operator++()

                        uint32_t value = (*this); // convert to 32 bit number
                        ++value; // Add 1
                        (*this) = address(value); // convert back to address and copy/move




                        Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:



                        ip::address::iterator ip::address::begin()

                        return data_.begin();


                        ip::address::const_iterator ip::address::end() const

                        return data_.end();


                        // I would just do the following the header:


                        iterator begin() return data_.begin();
                        iterator end() return data_.end();
                        const_iterator begin() const return data_.begin();
                        const_iterator end() const return data_.end();


                        You are of course missing a few:



                         const_iterator cbegin() const return data_.cbegin();
                        reverse_iterator rbegin() return data_.rbegin();

                        // You can add the end() versions.





                        share|improve this answer









                        $endgroup$

















                          1












                          $begingroup$

                          You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.



                           using Storage = std::array<value_type, 4>;
                          using iterator = Storage::iterator;
                          using const_iterator = Storage::const_iterator;
                          using reverse_iterator = Storage::reverse_iterator;
                          using const_reverse_iterator = Storage::const_reverse_iterator;
                          using size_type = Storage::size_type;


                          Now if you change the underlying storage type you only have to change it in one place.




                          What does it mean to increment/decrement an ip address?



                           /**
                          * @brief Prefix increment operator.
                          */
                          void operator++();


                          What scenario does this make sense?




                          If there is a test for equality:



                          bool operator==(const ip::address &first, const ip::address &second);


                          Then I would expect a test for inequality.




                          If there is an output operator:



                          std::ostream& operator<<(std::ostream& output, const ip::address &address);


                          Then I would expect an input operator.




                          The standard exceptions (except std::exception itself) already implement what(). You should inherit from one of these rather than std::exception (probably std::runtime_error.



                          class invalid_format_exception : public std::exception

                          std::string invalid_format_;
                          public:
                          invalid_format_exception(const std::string &invalid_format);
                          char const* what() const override;
                          ;


                          This becomes:



                          struct invalid_format_exception: std::runtime_error

                          using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.
                          ;



                          Are you sure that the IP address is always stored in big endian form?



                          data_[0] = value >> 24 & 0xFF;
                          data_[1] = value >> 16 & 0xFF;
                          data_[2] = value >> 8 & 0xFF;
                          data_[3] = value & 0xFF;


                          I would double check and also add a big comment that that is what you expect.




                          The increment operator looks complicated.

                          I think it can really be simplified by using some existing functions you have identified.



                          void ip::address::operator++()

                          uint32_t value = (*this); // convert to 32 bit number
                          ++value; // Add 1
                          (*this) = address(value); // convert back to address and copy/move




                          Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:



                          ip::address::iterator ip::address::begin()

                          return data_.begin();


                          ip::address::const_iterator ip::address::end() const

                          return data_.end();


                          // I would just do the following the header:


                          iterator begin() return data_.begin();
                          iterator end() return data_.end();
                          const_iterator begin() const return data_.begin();
                          const_iterator end() const return data_.end();


                          You are of course missing a few:



                           const_iterator cbegin() const return data_.cbegin();
                          reverse_iterator rbegin() return data_.rbegin();

                          // You can add the end() versions.





                          share|improve this answer









                          $endgroup$















                            1












                            1








                            1





                            $begingroup$

                            You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.



                             using Storage = std::array<value_type, 4>;
                            using iterator = Storage::iterator;
                            using const_iterator = Storage::const_iterator;
                            using reverse_iterator = Storage::reverse_iterator;
                            using const_reverse_iterator = Storage::const_reverse_iterator;
                            using size_type = Storage::size_type;


                            Now if you change the underlying storage type you only have to change it in one place.




                            What does it mean to increment/decrement an ip address?



                             /**
                            * @brief Prefix increment operator.
                            */
                            void operator++();


                            What scenario does this make sense?




                            If there is a test for equality:



                            bool operator==(const ip::address &first, const ip::address &second);


                            Then I would expect a test for inequality.




                            If there is an output operator:



                            std::ostream& operator<<(std::ostream& output, const ip::address &address);


                            Then I would expect an input operator.




                            The standard exceptions (except std::exception itself) already implement what(). You should inherit from one of these rather than std::exception (probably std::runtime_error.



                            class invalid_format_exception : public std::exception

                            std::string invalid_format_;
                            public:
                            invalid_format_exception(const std::string &invalid_format);
                            char const* what() const override;
                            ;


                            This becomes:



                            struct invalid_format_exception: std::runtime_error

                            using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.
                            ;



                            Are you sure that the IP address is always stored in big endian form?



                            data_[0] = value >> 24 & 0xFF;
                            data_[1] = value >> 16 & 0xFF;
                            data_[2] = value >> 8 & 0xFF;
                            data_[3] = value & 0xFF;


                            I would double check and also add a big comment that that is what you expect.




                            The increment operator looks complicated.

                            I think it can really be simplified by using some existing functions you have identified.



                            void ip::address::operator++()

                            uint32_t value = (*this); // convert to 32 bit number
                            ++value; // Add 1
                            (*this) = address(value); // convert back to address and copy/move




                            Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:



                            ip::address::iterator ip::address::begin()

                            return data_.begin();


                            ip::address::const_iterator ip::address::end() const

                            return data_.end();


                            // I would just do the following the header:


                            iterator begin() return data_.begin();
                            iterator end() return data_.end();
                            const_iterator begin() const return data_.begin();
                            const_iterator end() const return data_.end();


                            You are of course missing a few:



                             const_iterator cbegin() const return data_.cbegin();
                            reverse_iterator rbegin() return data_.rbegin();

                            // You can add the end() versions.





                            share|improve this answer









                            $endgroup$



                            You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.



                             using Storage = std::array<value_type, 4>;
                            using iterator = Storage::iterator;
                            using const_iterator = Storage::const_iterator;
                            using reverse_iterator = Storage::reverse_iterator;
                            using const_reverse_iterator = Storage::const_reverse_iterator;
                            using size_type = Storage::size_type;


                            Now if you change the underlying storage type you only have to change it in one place.




                            What does it mean to increment/decrement an ip address?



                             /**
                            * @brief Prefix increment operator.
                            */
                            void operator++();


                            What scenario does this make sense?




                            If there is a test for equality:



                            bool operator==(const ip::address &first, const ip::address &second);


                            Then I would expect a test for inequality.




                            If there is an output operator:



                            std::ostream& operator<<(std::ostream& output, const ip::address &address);


                            Then I would expect an input operator.




                            The standard exceptions (except std::exception itself) already implement what(). You should inherit from one of these rather than std::exception (probably std::runtime_error.



                            class invalid_format_exception : public std::exception

                            std::string invalid_format_;
                            public:
                            invalid_format_exception(const std::string &invalid_format);
                            char const* what() const override;
                            ;


                            This becomes:



                            struct invalid_format_exception: std::runtime_error

                            using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.
                            ;



                            Are you sure that the IP address is always stored in big endian form?



                            data_[0] = value >> 24 & 0xFF;
                            data_[1] = value >> 16 & 0xFF;
                            data_[2] = value >> 8 & 0xFF;
                            data_[3] = value & 0xFF;


                            I would double check and also add a big comment that that is what you expect.




                            The increment operator looks complicated.

                            I think it can really be simplified by using some existing functions you have identified.



                            void ip::address::operator++()

                            uint32_t value = (*this); // convert to 32 bit number
                            ++value; // Add 1
                            (*this) = address(value); // convert back to address and copy/move




                            Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:



                            ip::address::iterator ip::address::begin()

                            return data_.begin();


                            ip::address::const_iterator ip::address::end() const

                            return data_.end();


                            // I would just do the following the header:


                            iterator begin() return data_.begin();
                            iterator end() return data_.end();
                            const_iterator begin() const return data_.begin();
                            const_iterator end() const return data_.end();


                            You are of course missing a few:



                             const_iterator cbegin() const return data_.cbegin();
                            reverse_iterator rbegin() return data_.rbegin();

                            // You can add the end() versions.






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 1 hour ago









                            Martin YorkMartin York

                            74.2k488272




                            74.2k488272





















                                1












                                $begingroup$

                                I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a range of octets. What benefit do you gain from that? IMHO: none. None benefit.




                                As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:



                                ::ip::address& ip::address::operator++(int)

                                auto result(*this);
                                ++(*this);
                                return result;



                                This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to compile with -W -Wall -Wextra and fix all the warnings prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!




                                ip::address::iterator ip::address::begin()

                                return data_.begin();


                                ip::address::const_iterator ip::address::end() const

                                return data_.end();



                                It is super weird to me that you define these member functions in the order "nonconst begin, const end, const begin, nonconst end." That's harmless, but it's just weird. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:



                                 iterator begin() return data_.begin(); 
                                iterator end() return data_.end();
                                const_iterator begin() const return data_.begin();
                                const_iterator end() const return data_.end();
                                private:
                                std::array<value_type, 4> data_;


                                Also, all four of these methods should probably be declared noexcept.




                                Overloaded comparison operators should always be defined in-line in the body of the class, using the "hidden friend" (a.k.a. "ADL friend," a.k.a. "Barton-Nackman") trick. That is, instead of



                                class address ... ;

                                bool operator<(const ip::address &first, const ip::address &second);

                                bool ip::operator<(const ip::address& first, const ip::address& second)

                                return (uint32_t)first() < (uint32_t)second();



                                you should write simply



                                class address 
                                // ...

                                friend bool operator<(const address& a, const address& b)
                                return uint32_t(a()) < uint32_t(b());

                                ;


                                Notice that I switched your type-casts from C style to constructor-style, a.k.a. "Python style," just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose first and second to simply a and b: we don't need long names for these extremely locally scoped variables.



                                But wait, there's more! I initially assumed that first() was a typo — but it's not! You actually declared an overloaded operator():



                                 /**
                                * @brief Implicit conversion to an unsigned 32 bit integer.
                                */
                                uint32_t operator()() const;


                                Why on earth is this an overloaded function-call operator instead of a conversion operator? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function ip::to_string(const address&)? Why is the conversion to uint32_t not implemented as ip::to_uint32(const address&)?



                                Consistency is important. Also, compatibility with the rest of the language is important. When you overload operator(), you're making ip::address "callable," which means you're enabling your clients to write things like



                                ip::address myAddress(127, 0, 0, 1);
                                std::function<int()> f = myAddress; // !!
                                assert(f() == 0x7F000001);


                                Just as with the iterator/range-of-octets business, this functionality strikes me as fundamentally not what an IP address ought to be about. IP addresses aren't ranges, and IP addresses aren't callables. They should be just addresses. To the extent that your ip::address is anything other than just an address, you have actually failed in your stated goal of "modeling an IP address"!




                                Your operator<< should also be defined in-line.



                                Anytime you provide operator==, you should also provide operator!= — the language doesn't (yet) provide it for you automatically.



                                Anytime you provide operator<, you should also provide operator<=, >, and >= — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have operator<=> to play with!)




                                void ip::address::operator++()

                                auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

                                return data < 255;
                                );

                                if(location != std::rend(data_))

                                const auto r_index = std::distance(data_.rbegin(), location);
                                auto index = 4 - r_index - 1;
                                data_[index]++;




                                It's odd that you write data_.rend() in one place and std::rend(data_) in the other. I recommend the former in both cases, simply because it's shorter.



                                However, doesn't this code "increment" address(0, 0, 0, 255) to address(0, 0, 1, 255) instead of to address(0, 0, 1, 0)? If so, oops! IMO the clearest and simplest way to write this "odometer algorithm" is simply



                                address& operator++() noexcept

                                if (++data_[3] == 0)
                                if (++data_[2] == 0)
                                if (++data_[1] == 0)
                                ++data_[0];



                                return *this;



                                Short and sweet. Arguably it's overly complicated and "clever" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines longer, and (AFAICT) doesn't even work. So feel free to reduce the "cleverness" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.






                                share|improve this answer









                                $endgroup$

















                                  1












                                  $begingroup$

                                  I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a range of octets. What benefit do you gain from that? IMHO: none. None benefit.




                                  As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:



                                  ::ip::address& ip::address::operator++(int)

                                  auto result(*this);
                                  ++(*this);
                                  return result;



                                  This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to compile with -W -Wall -Wextra and fix all the warnings prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!




                                  ip::address::iterator ip::address::begin()

                                  return data_.begin();


                                  ip::address::const_iterator ip::address::end() const

                                  return data_.end();



                                  It is super weird to me that you define these member functions in the order "nonconst begin, const end, const begin, nonconst end." That's harmless, but it's just weird. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:



                                   iterator begin() return data_.begin(); 
                                  iterator end() return data_.end();
                                  const_iterator begin() const return data_.begin();
                                  const_iterator end() const return data_.end();
                                  private:
                                  std::array<value_type, 4> data_;


                                  Also, all four of these methods should probably be declared noexcept.




                                  Overloaded comparison operators should always be defined in-line in the body of the class, using the "hidden friend" (a.k.a. "ADL friend," a.k.a. "Barton-Nackman") trick. That is, instead of



                                  class address ... ;

                                  bool operator<(const ip::address &first, const ip::address &second);

                                  bool ip::operator<(const ip::address& first, const ip::address& second)

                                  return (uint32_t)first() < (uint32_t)second();



                                  you should write simply



                                  class address 
                                  // ...

                                  friend bool operator<(const address& a, const address& b)
                                  return uint32_t(a()) < uint32_t(b());

                                  ;


                                  Notice that I switched your type-casts from C style to constructor-style, a.k.a. "Python style," just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose first and second to simply a and b: we don't need long names for these extremely locally scoped variables.



                                  But wait, there's more! I initially assumed that first() was a typo — but it's not! You actually declared an overloaded operator():



                                   /**
                                  * @brief Implicit conversion to an unsigned 32 bit integer.
                                  */
                                  uint32_t operator()() const;


                                  Why on earth is this an overloaded function-call operator instead of a conversion operator? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function ip::to_string(const address&)? Why is the conversion to uint32_t not implemented as ip::to_uint32(const address&)?



                                  Consistency is important. Also, compatibility with the rest of the language is important. When you overload operator(), you're making ip::address "callable," which means you're enabling your clients to write things like



                                  ip::address myAddress(127, 0, 0, 1);
                                  std::function<int()> f = myAddress; // !!
                                  assert(f() == 0x7F000001);


                                  Just as with the iterator/range-of-octets business, this functionality strikes me as fundamentally not what an IP address ought to be about. IP addresses aren't ranges, and IP addresses aren't callables. They should be just addresses. To the extent that your ip::address is anything other than just an address, you have actually failed in your stated goal of "modeling an IP address"!




                                  Your operator<< should also be defined in-line.



                                  Anytime you provide operator==, you should also provide operator!= — the language doesn't (yet) provide it for you automatically.



                                  Anytime you provide operator<, you should also provide operator<=, >, and >= — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have operator<=> to play with!)




                                  void ip::address::operator++()

                                  auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

                                  return data < 255;
                                  );

                                  if(location != std::rend(data_))

                                  const auto r_index = std::distance(data_.rbegin(), location);
                                  auto index = 4 - r_index - 1;
                                  data_[index]++;




                                  It's odd that you write data_.rend() in one place and std::rend(data_) in the other. I recommend the former in both cases, simply because it's shorter.



                                  However, doesn't this code "increment" address(0, 0, 0, 255) to address(0, 0, 1, 255) instead of to address(0, 0, 1, 0)? If so, oops! IMO the clearest and simplest way to write this "odometer algorithm" is simply



                                  address& operator++() noexcept

                                  if (++data_[3] == 0)
                                  if (++data_[2] == 0)
                                  if (++data_[1] == 0)
                                  ++data_[0];



                                  return *this;



                                  Short and sweet. Arguably it's overly complicated and "clever" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines longer, and (AFAICT) doesn't even work. So feel free to reduce the "cleverness" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.






                                  share|improve this answer









                                  $endgroup$















                                    1












                                    1








                                    1





                                    $begingroup$

                                    I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a range of octets. What benefit do you gain from that? IMHO: none. None benefit.




                                    As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:



                                    ::ip::address& ip::address::operator++(int)

                                    auto result(*this);
                                    ++(*this);
                                    return result;



                                    This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to compile with -W -Wall -Wextra and fix all the warnings prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!




                                    ip::address::iterator ip::address::begin()

                                    return data_.begin();


                                    ip::address::const_iterator ip::address::end() const

                                    return data_.end();



                                    It is super weird to me that you define these member functions in the order "nonconst begin, const end, const begin, nonconst end." That's harmless, but it's just weird. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:



                                     iterator begin() return data_.begin(); 
                                    iterator end() return data_.end();
                                    const_iterator begin() const return data_.begin();
                                    const_iterator end() const return data_.end();
                                    private:
                                    std::array<value_type, 4> data_;


                                    Also, all four of these methods should probably be declared noexcept.




                                    Overloaded comparison operators should always be defined in-line in the body of the class, using the "hidden friend" (a.k.a. "ADL friend," a.k.a. "Barton-Nackman") trick. That is, instead of



                                    class address ... ;

                                    bool operator<(const ip::address &first, const ip::address &second);

                                    bool ip::operator<(const ip::address& first, const ip::address& second)

                                    return (uint32_t)first() < (uint32_t)second();



                                    you should write simply



                                    class address 
                                    // ...

                                    friend bool operator<(const address& a, const address& b)
                                    return uint32_t(a()) < uint32_t(b());

                                    ;


                                    Notice that I switched your type-casts from C style to constructor-style, a.k.a. "Python style," just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose first and second to simply a and b: we don't need long names for these extremely locally scoped variables.



                                    But wait, there's more! I initially assumed that first() was a typo — but it's not! You actually declared an overloaded operator():



                                     /**
                                    * @brief Implicit conversion to an unsigned 32 bit integer.
                                    */
                                    uint32_t operator()() const;


                                    Why on earth is this an overloaded function-call operator instead of a conversion operator? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function ip::to_string(const address&)? Why is the conversion to uint32_t not implemented as ip::to_uint32(const address&)?



                                    Consistency is important. Also, compatibility with the rest of the language is important. When you overload operator(), you're making ip::address "callable," which means you're enabling your clients to write things like



                                    ip::address myAddress(127, 0, 0, 1);
                                    std::function<int()> f = myAddress; // !!
                                    assert(f() == 0x7F000001);


                                    Just as with the iterator/range-of-octets business, this functionality strikes me as fundamentally not what an IP address ought to be about. IP addresses aren't ranges, and IP addresses aren't callables. They should be just addresses. To the extent that your ip::address is anything other than just an address, you have actually failed in your stated goal of "modeling an IP address"!




                                    Your operator<< should also be defined in-line.



                                    Anytime you provide operator==, you should also provide operator!= — the language doesn't (yet) provide it for you automatically.



                                    Anytime you provide operator<, you should also provide operator<=, >, and >= — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have operator<=> to play with!)




                                    void ip::address::operator++()

                                    auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

                                    return data < 255;
                                    );

                                    if(location != std::rend(data_))

                                    const auto r_index = std::distance(data_.rbegin(), location);
                                    auto index = 4 - r_index - 1;
                                    data_[index]++;




                                    It's odd that you write data_.rend() in one place and std::rend(data_) in the other. I recommend the former in both cases, simply because it's shorter.



                                    However, doesn't this code "increment" address(0, 0, 0, 255) to address(0, 0, 1, 255) instead of to address(0, 0, 1, 0)? If so, oops! IMO the clearest and simplest way to write this "odometer algorithm" is simply



                                    address& operator++() noexcept

                                    if (++data_[3] == 0)
                                    if (++data_[2] == 0)
                                    if (++data_[1] == 0)
                                    ++data_[0];



                                    return *this;



                                    Short and sweet. Arguably it's overly complicated and "clever" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines longer, and (AFAICT) doesn't even work. So feel free to reduce the "cleverness" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.






                                    share|improve this answer









                                    $endgroup$



                                    I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a range of octets. What benefit do you gain from that? IMHO: none. None benefit.




                                    As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:



                                    ::ip::address& ip::address::operator++(int)

                                    auto result(*this);
                                    ++(*this);
                                    return result;



                                    This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to compile with -W -Wall -Wextra and fix all the warnings prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!




                                    ip::address::iterator ip::address::begin()

                                    return data_.begin();


                                    ip::address::const_iterator ip::address::end() const

                                    return data_.end();



                                    It is super weird to me that you define these member functions in the order "nonconst begin, const end, const begin, nonconst end." That's harmless, but it's just weird. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:



                                     iterator begin() return data_.begin(); 
                                    iterator end() return data_.end();
                                    const_iterator begin() const return data_.begin();
                                    const_iterator end() const return data_.end();
                                    private:
                                    std::array<value_type, 4> data_;


                                    Also, all four of these methods should probably be declared noexcept.




                                    Overloaded comparison operators should always be defined in-line in the body of the class, using the "hidden friend" (a.k.a. "ADL friend," a.k.a. "Barton-Nackman") trick. That is, instead of



                                    class address ... ;

                                    bool operator<(const ip::address &first, const ip::address &second);

                                    bool ip::operator<(const ip::address& first, const ip::address& second)

                                    return (uint32_t)first() < (uint32_t)second();



                                    you should write simply



                                    class address 
                                    // ...

                                    friend bool operator<(const address& a, const address& b)
                                    return uint32_t(a()) < uint32_t(b());

                                    ;


                                    Notice that I switched your type-casts from C style to constructor-style, a.k.a. "Python style," just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose first and second to simply a and b: we don't need long names for these extremely locally scoped variables.



                                    But wait, there's more! I initially assumed that first() was a typo — but it's not! You actually declared an overloaded operator():



                                     /**
                                    * @brief Implicit conversion to an unsigned 32 bit integer.
                                    */
                                    uint32_t operator()() const;


                                    Why on earth is this an overloaded function-call operator instead of a conversion operator? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function ip::to_string(const address&)? Why is the conversion to uint32_t not implemented as ip::to_uint32(const address&)?



                                    Consistency is important. Also, compatibility with the rest of the language is important. When you overload operator(), you're making ip::address "callable," which means you're enabling your clients to write things like



                                    ip::address myAddress(127, 0, 0, 1);
                                    std::function<int()> f = myAddress; // !!
                                    assert(f() == 0x7F000001);


                                    Just as with the iterator/range-of-octets business, this functionality strikes me as fundamentally not what an IP address ought to be about. IP addresses aren't ranges, and IP addresses aren't callables. They should be just addresses. To the extent that your ip::address is anything other than just an address, you have actually failed in your stated goal of "modeling an IP address"!




                                    Your operator<< should also be defined in-line.



                                    Anytime you provide operator==, you should also provide operator!= — the language doesn't (yet) provide it for you automatically.



                                    Anytime you provide operator<, you should also provide operator<=, >, and >= — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have operator<=> to play with!)




                                    void ip::address::operator++()

                                    auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)

                                    return data < 255;
                                    );

                                    if(location != std::rend(data_))

                                    const auto r_index = std::distance(data_.rbegin(), location);
                                    auto index = 4 - r_index - 1;
                                    data_[index]++;




                                    It's odd that you write data_.rend() in one place and std::rend(data_) in the other. I recommend the former in both cases, simply because it's shorter.



                                    However, doesn't this code "increment" address(0, 0, 0, 255) to address(0, 0, 1, 255) instead of to address(0, 0, 1, 0)? If so, oops! IMO the clearest and simplest way to write this "odometer algorithm" is simply



                                    address& operator++() noexcept

                                    if (++data_[3] == 0)
                                    if (++data_[2] == 0)
                                    if (++data_[1] == 0)
                                    ++data_[0];



                                    return *this;



                                    Short and sweet. Arguably it's overly complicated and "clever" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines longer, and (AFAICT) doesn't even work. So feel free to reduce the "cleverness" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 1 hour ago









                                    QuuxplusoneQuuxplusone

                                    13k12063




                                    13k12063




















                                        Developer Paul is a new contributor. Be nice, and check out our Code of Conduct.









                                        draft saved

                                        draft discarded


















                                        Developer Paul is a new contributor. Be nice, and check out our Code of Conduct.












                                        Developer Paul is a new contributor. Be nice, and check out our Code of Conduct.











                                        Developer Paul is a new contributor. Be nice, and check out our Code of Conduct.














                                        Thanks for contributing an answer to Code Review Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid …


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        Use MathJax to format equations. MathJax reference.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216894%2fmodeling-an-ip-address%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Is it wise to focus on putting odd beats on left when playing double bass drums?What does the tie across other different notes mean?How to improve right hand picking/strumming technique for electric and acoustic guitar?How fast is the BPM should you start to use double bass pedal?Alternative or more advanced methods for counting rhythmsLost direction in practicing drumsIs there any way at all to tell if these measures are 6/4 vs. 3/2?Why is alberti bass so tiring?How does 'meter' differ from 'rhythm' in music?Rhythm question about piano sheet notationWhy is Bach's Cello Suite 1 written in 16th notes

                                        map list to bin numbersquantilization (if that is a word)Map efficiently over duplicates in listGenerating a list of cubefree numbersIs there an equivalent to MATLAB's linspace?Convert a list of hexadecimal numbers to decimalTaking one list Mod a second listlist of items and group of alternative itemsHow find numbers in this list of inequalities?Selecting list entries with a True False index list of similar lengthReplace element in array by checking condition in another listAttempting to fill a table with the number of elements in each bin and make a table with the elements in the bins?

                                        History of India Contents Prehistoric era (until c. 3300 BCE) Bronze Age – "First urbanisation" (c. 3300 – c. 1800 BCE) Climate change, de-urbanisation, and Indo-Aryan migrations (c.1800 – 1500 BCE) Iron Age - Vedic period (c. 1500 – c. 600 BCE) "Second urbanisation" (c. 600 – c. 200 BCE) Classical to early medieval periods (c. 200 BCE – c. 1200 CE) Late medieval period (c. 1200 – 1526 CE) Early modern period (c. 1526–1858 CE) Modern period and independence (after c. 1850 CE) Historiography See also References Further reading External links Navigation menureviewedee[update]The crisisThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and GeneticsThe Ancient Indus: Urbanism, Economy, and Society"Indus River Valley Civilizations"The Ancient Indus: Urbanism, Economy, and Society"India before the British: The Mughal Empire and its Rivals, 1526–1857"Why Europe Grew Rich and Asia Did Not: Global Economic Divergence, 1600–1850Development Centre Studies The World Economy Historical Statistics: Historical StatisticsDeveloping cultures: case studiesEthnic Groups of South Asia and the Pacific: An Encyclopedia: An Encyclopedia"Indian Economy During British Rule""Economic Impact of the British Rule in India | Indian History"The Bone Readers: Science and Politics in Human Origins Research"Out of Africa: new hypotheses and evidence for the dispersal of Homo sapiens along the Indian Ocean rim"10.3109/0301446100363924920334598"Genetic and archaeological perspectives on the initial modern human colonization of southern Asia"2013PNAS..11010699M10.1073/pnas.1306043110369678523754394"Edakkal Caves|Places Around in Wayanad"Protecting megaliths to keep history alive The Hindu daily"Archaeologists rock solid behind Edakkal Cave"The Global Prehistory of Human Migration"Indus Valley 2,000 years older than thought"the original"Stepwells -Cosmology of Subterranean Architecture as seen in Adalaj"A History of Ancient and Early medieval India : from the Stone Age to the 12th century"Stone celts in Harappa"the original"Peoples and languages in pre-islamic Indus valley"the original"The Sindhi language"the originalThe Aryan chromosome"Fluvial landscapes of the Harappan Civilization"2012PNAS..109E1688G10.1073/pnas.1112743109338705422645375"Is River Ghaggar, Saraswati? Geochemical Constraints""An Ancient Civilization, Upended by Climate Change""Huge Ancient Civilization's Collapse Explained"2003GeoRL..30.1425S10.1029/2002GL0168222006QSRv...25.1283M10.1016/j.quascirev.2005.10.0122011QuInt.229..140M10.1016/j.quaint.2009.11.012Climate Change and the Course of Global History: A Rough JourneyA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyA History of Ancient and Mediaeval India: From the Stone Age to the 12th CenturyAntennae SwordA History of IndiaA History of IndiaAn Introduction to Hinduism"India: The Late 2nd Millennium and the Reemergence of Urbanism"The Coinage of Ancient IndiaA Sanskrit reader: with vocabulary and notesPedigree: the origins of words from nature"Early Sanskritization. Origins and Development of the Kuru State"10.11588/ejvs.1995.4.823The Sanskrit epics, Part 2The City in South AsiaThe UpanishadsAn Introduction to HinduismReligions of the World, Second Edition: A Comprehensive Encyclopedia of Beliefs and PracticesA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyEarly India: From the Origins to AD 1300Republics in ancient Indiapp. 83ff"Magadha Empire""Lumbini Development Trust: Restoring the Lumbini Garden"the originalThe great armies of antiquityarchived"The Achaemenid Persian Empire (550–330 B.C.)""East–West Orientation of Historical Empires"1076-156X"Dinner on the Grand Trunk Road"10.2307/32502263250226"Silappathikaram Tamil Literature"the originalManimekalai – English transliteration of Tamil originalIndian Temple Architecture: Form and Transformation : the Karṇāṭa Drāviḍa Tradition, 7th to 13th CenturiesBuddhist ArchitectureA History of India"The World Economy (GDP) : Historical Statistics by Professor Angus Maddison"The World Economy – Volume 1: A Millennial Perspective and Volume 2: Historical Statistics10.2307/32502140004-36483250214A Comprehensive History of India: Volume 2Between the Empires: Society in India, 300 to 400Emergence of Viṣṇu and Śiva Images in India: Numismatic and Sculptural Evidence"Parthian Pair of Earrings"the originalThe Medical Times and Gazette, Volume 1Greatest emporium in the worldThe Cambridge History of Ancient China: From the Origins of Civilization to 221 BCBuddhist Records of the Western WorldArchaeology in Soviet Central AsiaThe Grandeur of Gandhara: The Ancient Buddhist Civilization of the Swat, Peshawar, Kabul and Indus ValleysIndian Sculpture: Circa 500 B.C.-A.D. 700"The History of Pakistan: The Kushans"Gupta Dynasty – MSN Encartathe original"India – Historical Setting – The Classical Age – Gupta and Harsha""Gupta Dynasty, Golden Age Of India"the original"The Age of the Guptas and After"the originalNumber Theory and Its History"Gupta dynasty (Indian dynasty)""Gupta dynasty: empire in 4th century"the original"The Story of India – Photo Gallery"The ASI say499315420"Pallava script"p. 145"CNG: eAuction 329. INDIA, Post-Gupta (Ganges Valley). Vardhanas of Thanesar and Kanauj. Harshavardhana. Circa AD 606–647. AR Drachm (13mm, 2.28 g, 1h)""Harsha""Sthanvishvara (historical region, India)""Harsha (Indian emperor)"Shyama Kumar Chattopadhyaya (2000) The Philosophy of Sankar's Advaita VedantaShankara's IntroductionShankara's Introduction19373677Shankara's IntroductionIs The Buddhist 'No-Self' Doctrine Compatible With Pursuing Nirvana?The Seven Spiritual Laws Of YogaIndia: The Ancient Past. A History of the Indian-Subcontinent from 7000 BC to AD 1200The Kashmir Series: Glimpses of Kashmiri Culture – Vivekananda Kendra, Kanyakumari (p. 57).Al-Hind: Early Medieval India and the Expansion of Islam, 7th–11th CenturiesHistory of GopāchalaLand of Two Rivers: A History of Bengal from the Mahabharata to MujibEuropean Trade and Colonial ConquestA History of IndiaA Comprehensive History Of Ancient India (3 Vol. Set)"The Last Years of Cholas: The decline and fall of a dynasty"the originalFascinating Hindutva: Saffron Politics and Dalit MobilisationGazetteer of the province of OudhAl- Hind: The slave kings and the Islamic conquest. 2"Shahi Family"The Cambridge history of Islam"Ameer Nasir-ood-deen Subooktugeen"Gazetteer of the Attock District, 1930, Part 1Land of seven rivers: History of India's GeographyTemple Desecration and Indo-Muslim StatesIslam in South Asia: A Short HistoryBeyond Orientalism: The Work of Wilhelm Halbfass and Its Impact on Indian and Cross-cultural StudiesThe Making of Terrorism in Pakistan: Historical and Social Roots of ExtremismOrnament in Indian ArchitectureA historical review of Hindu India: 300 B.C. to 1200 A.D."Indian States and Union Territories"Islam in South Asia: A Short HistoryA Brief History of the Indian PeoplesThe Modern ReviewDelhi Sultanate"Battuta's Travels: Delhi, capital of Muslim India"the original"Timur – conquest of India"the originalIndia HandbookBhaktiThe Four Denomination of Hinduism10.1007/s11407-008-9049-925691067"Vijayanagara Research Project::Elephant Stables"10.2307/26465262646526Historical Dictionary of the TamilsBihar General Knowledge DigestMapping Bihar: From Medieval to Modern TimesPopular Literature and Pre-modern Societies in South AsiaA manual of the Kistna district in the presidency of MadrasAncient Indian History and CivilizationFragmented Memories: Struggling to be Tai-Ahom in India"The Islamic World to 1600: Rise of the Great Islamic Empires (The Mughal Empire)"the originalDynasties: A Global History of Power, 1300–1800, p. 105"Whose fort is it anyway"10.1111/0020-8833.000532600793Development Centre Studies The World Economy Historical Statistics: Historical Statistics"India's Deindustrialization in the 18th and 19th Centuries"The Mughal Empire, p. 190"The Long Globalization and Textile Producers in India"The Mughal World: Life in India's Last Golden AgeAurangzeb: The Life and Legacy of India's Most Controversial KingIn the Shadow of the Taj: A Portrait of Agra"Iran in the Age of the Raj"p. 8610.2307/20539802053980Delhi, the Capital of IndiaAn Advanced History of Modern India"Journal of the Tanjore Maharaja Serfoji's Sarasvati Mahal Library"The Rediscovery of India: A New SubcontinentIslamic Renaissance In South Asia (1707–1867) : The Role Of Shah Waliallah & His SuccessorsAn Advanced History of Modern IndiaThe Great Maratha Mahadaji Scindia"Full text of "Selections from the papers of Lord Metcalfe; late governor-general of India, governor of Jamaica, and governor-general of Canada""The Discovery Of IndiaThe Sacred City of the Hindus: An Account of Benares in Ancient and Modern TimesResurrecting Banaras: Urban Space, Architecture and Religious BoundariesFaith & Philosophy of Sikhism"Missiles mainstay of Pak's N-arsenal"History Modern India By S.N. Sen"Sirajuddaula"ArchivedLongman History & Civics (Dual Government in Bengal)Madhya Pradesh National Means-Cum-Merit Scholarship Exam (Warren Hasting's system of Dual Government)A Military History of Britain: from 1775 to the PresentIndian Cultural Heritage Perspective For TourismHindu Rulers, Muslim Subjects: Islam, Rights, and the History of KashmirIndian HistoryAn Atlas and Survey of South Asian HistoryAn Historical Account of the British Trade Over the Caspian SeaIndian Merchants and Eurasian Trade, 1600–1750The Indian diaspora in Central Asia and its trade, 1550–1900From Constantinople to the home of Omar Khayyam: travels in Transcaucasia and northern Persia for historic and literary researchA journey from Bengal to England: through the northern part of India, Kashmire, Afghanistan, and Persia, and into Russia, by the Caspian-SeaA Second Journey through Persia, Armenia, and Asia Minor, to Constantinople, between the Years 1810 and 1816Reports from the consuls of the United States, 1887Portugal and its Empire, 1250–1800 (Collected Essays in Memory of Glenn J. Ames).: Portuguese Studies Review, Vol. 17, No. 1The Dutch Power in Kerala, 1729–1758http://mod.nic.inArchivedDossier Goa – A Recusa do Sacrifício InútilAn Imperial Crisis in British India: The Manipur Uprising of 1891The Truth of Babri Mosque"Kolkata (Calcutta) : History"the original"Robert Clive, Baron Clive, 'Clive of India', 1725–1774""The Transformation from a Pre-Colonial to a Colonial Order: The Case of India"10.2307/25955872595587A versatile geniusArchived10.1109/MWSYM.1997.602854"Rabindranath Tagore on Education"the original"Essay on 'Derozio and the Young Bengal Movement'"Poverty and Famines: An Essay on Entitlement and Deprivation"Plague"the originalPopulation Growth and Land Use"Reintegrating India with the World Economy""Census Of India 1931"A history of modern India, 1480–1950"'India's well-timed diversification of army helped democracy' | Business Standard News"Bal Gangadhar Tilak: Struggle for Swaraj"Participants from the Indian subcontinent in the First World War""Commonwealth War Graves Commission Annual Report 2007–2008 Online"the original1462689197110.1017/s0010417500016534178920Eurocentrism: a marxian critical realist critique"Ranjit Guha, "On Some Aspects of Historiography of Colonial India""10.2307/2168385216838510.7202/016593ar"Harvard scholar says the idea of India dates to a much earlier time than the British or the Mughals""In The Footsteps of Pilgrims""India's spiritual landscape: The heavens and the earth""India: A Sacred Geography by Diana L Eck – review"Modern India: The Origins of an Asian Democracy10.2307/21694222169422964322464"The Indian Subcontinent and 'Out of Africa 1'"254043308Encyclopedia of World ReligionsThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and Genetics"The Early Paleolithic of the Indian Subcontinent: Hominin Colonization, Dispersals and Occupation History"Ancient Indian History and CivilizationAncient Indian Social History: Some Interpretationsthe originalIndia Before EuropeA Concise History of Modern India"The beginning of the historical period, c. 500–150 BCE"full textA History of Indiathe originalexcerpt and text searchexcerptexcerptAn Economic History of India: From Pre-Colonial Times to 1991excerpt and text searchexcerpt and text searchIndia as known to the ancient world10.1111/j.1468-0289.1985.tb00391.x2597191onlineThe History of India, as told by its own historians. The Muhammadan Periodonline editionHans William Brown research collection on 19th-century missionary work in India, 1882–1932, Ms. Coll. 1033, Kislak Center for Special Collections, Rare Books and Manuscripts, University of Pennsylvaniaee