Boost logo

Boost :

Subject: [boost] [core] Determining interest for two new classes: readonly and newtype
From: Sam Kellett (samkellett_at_[hidden])
Date: 2015-08-16 10:23:58


Hey, I have two classes I've developed that have been used in my own
projects that I think could have a place in Boost. They are outlined below.

readonly<T>:

This is a wrapper class for a type to replace a const-type field in a
movable class. It has const access to the type so can't modify except for
the move constructor and move assignment operator.

This solves the problem that no fields in a movable class can be const
which can cloud the intentions of a field.

readonly copies the accessor patterns seen in classes such as optional and
the smart pointer collection.

Example:

struct foo
{
  foo() : str("hello world") {}

  readonly<std::string> str;
};

foo f;
auto g = std::move(f);

static_assert(std::is_move_constructible<foo>{}, "");

std::cout << *g.str << std::endl;
g.str->clear() // error: non-const method.

-----

newtype<N, T>

This is shamelessly ripped off from Haskell and provides strongly-typed
typedefs to C++.

It actually has two template parameters, one is an incomplete type that
provides a unique identifier for this typedef. I've opted to use the name
of the typedef with an '_t' suffix, the second is the raw type that it
contains.

Like readonly the underlying type can be accessed by operator*, operator->
and get() methods.

Example:

using age = newtype<struct age_t, int>;
age a{25};

using byte = newtype<struct byte_t, int>;
byte b{42};

// do something with bytes (*not* any old int).
void bar(const byte);

bar(a); // error: wrong type wanted 'byte' got 'age'
bar(b); // okay
bar(89); // error: wrong type wanted 'byte' got 'int'

assert(*b == 42);

Any thoughts on the design and/or their place in Boost would be much
appreciated.

Cheers,
Sam


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk