Boost logo

Boost Users :

From: Eugene M. Kim (gene_at_[hidden])
Date: 2008-01-23 05:23:59


Greetings,

On UNIX-like platforms,
boost::asio::detail::socket_option::{boolean,integer} templates are very
useful when defining socket option classes for non-standard options that
are supported by the platform, e.g.:

namespace so = boost::asio::detail::socket_option;

typedef so::boolean<SOL_SOCKET, SO_REUSEADDR> reuse_addr;
typedef so::boolean<SOL_SOCKET, SO_REUSEPORT> reuse_port;
typedef so::boolean<SOL_SOCKET, SO_ERROR> pending_error;
typedef so::integer<SOL_SOCKET, SO_SNDLOWAT> send_low_watermark;
typedef so::integer<SOL_SOCKET, SO_RCVLOWAT> recv_low_watermark;
typedef so::boolean<IPPROTO_IP, IP_HDRINCL> include_header;
typedef so::boolean<IPPROTO_IP, IP_DONTFRAG> do_not_fragment;
typedef so::integer<IPPROTO_IP, IP_TOS> type_of_service;
typedef so::integer<IPPROTO_IP, IP_TTL> time_to_live;

... and so on.

It is not suitable to include these non-standard options in the asio
library itself, but it seems justifiable to move the boolean/integer
templates out of boost::asio::detail and into boost::asio.

Also, many socket options take a C struct as an argument, so a template
for such options might be useful as well:

template <int Level, int Name, class Value>
class typed
: public Value
{
  typedef Value value;

  template <typename Protocol>
  int level(const Protocol &) const
  {
    return Level;
  }

  template <typename Protocol>
  int name(const Protocol &) const
  {
    return Name;
  }

  template <typename Protocol>
  value *data(const Protocol &)
  {
    return (value *)this;
  }

  template <typename Protocol>
  std::size_t size(const Protocol &) const
  {
    return sizeof(Value);
  }

  template <typename Protocol>
  void resize(const Protocol &, std::size_t s) const
  {
    if (s != sizeof(Value))
      throw std::length_error("resizing fixed-length socket option");
  }
};

Then it becomes trivial to define and use such socket options:

typedef typed<SOL_SOCKET, SO_SNDTIMEO, struct ::timeval> send_timeout;
typedef typed<SOL_SOCKET, SO_RCVTIMEO, struct ::timeval> recv_timeout;

send_timeout sndtimeo;
sndtimeo.tv_sec = 1;
sndtimeo.tv_usec = 0;

Would this template be appropriate for inclusion in a future version of
asio? Just my $.02.

Cheers,
Eugene


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net