I am designing a class that has two constructors with single integer arguments that have separate semantics.
template <typename value_t>
class Numeric {
value_t value_;
public:
Numeric(value_t value) : value_(value) {}
Numeric(long l) { /* computes value_ from l */ }
Numeric(double d) { /* computes value_ from d */ }
Numeric(std::string bstring) { /* computes value_ from binary string */ }
// ...
};
value_t
must be an integral type in this case, it could even be an alias to long
(in which case this wouldn't even compile). Even if it wasn't a type alias to long
, I'm not so sure how integer promotions might confuse the two constructors.
The idea is I want to support the user constructing by giving the underlying representation, or by giving it any possible numeric representation, which would then convert to the underlying representation (A.K.A value_t
).
What's the best way to segregate the constructors?
I would recommend making the constructors
private
and using instead static functions to "create" your instances. The static functions can have meaningful names, in order to explicitly tell the users what to expect from each:And even if you still want to use those constructors instead of assigning the internal variable, you can put them in the private section and call them from the
static
functions, so the users will never be able to call them directly.