paperjam
paperjam

Reputation: 8528

C++ non-zero default value for numeric types - reinvention?

I have in mind a construct like this:

template <typename T, T defaultValue>
struct Numeric
{
    Numeric(T t=defaultValue) : value(t) { }
    T value;
    T operator=()(T t);
    operator T();
};

I might use it like this:

std::vector<Numeric<bool, true> > nothingButTheTruth;

My question is simple: Is this a good approach and if so, does something like this exist in a standard library or Boost?

Upvotes: 4

Views: 259

Answers (1)

smparkes
smparkes

Reputation: 14063

The pattern I see more commonly is to parameterize the container, not the type.

There are a lot of downsides to doing it your way:

  • While you provide assignment and conversion, you can't actually bind a bool& to a Numeric<bool, true>.
  • A vector<bool> and a vector<Numeric<bool, true> > are unrelated types.

This gets pretty painful pretty quickly. I wouldn't do it, but perhaps you have a strong use case.

Upvotes: 2

Related Questions