-
Notifications
You must be signed in to change notification settings - Fork 37
Description
After hesitating to use a strong type library for production code for quite a long time, I just started using this library in one of my projects.
I've decided in favour of this library, due to its broad C++ language support and due to the number of contributors. Using this library is easy and the documentation in the README is concise but good.
I do wonder though, if it is possible to add constructor invariant checking using this library. I haven't been able to find anything in the documentation, that's why I'm asking this question.
Consider that I'd like to implement a strong type FirstName, that does not allow to store an empty ("") name.
The best code I've been able to come up with is this:
class FirstName final : public strong::type<std::string, struct FirstName_, strong::equality, strong::ostreamable> {
public:
explicit FirstName(std::string value)
: type<std::string, FirstName_, strong::equality, strong::ostreamable> { std::move(value) }
{
if (_val.empty()) {
throw std::invalid_argument { "The value of 'FirstName' may not be empty." };
}
}
};
This could be "simplified" as follows, with the cost of having a useless visible type alias.
using FirstNameBase = strong::type<std::string, struct FirstNameBase_, strong::equality, strong::ostreamable>;
class FirstName final : public FirstNameBase {
public:
explicit FirstName(std::string value)
: FirstNameBase { std::move(value) }
{
// Check constructor invariant.
if (_val.empty()) {
throw std::invalid_argument { "The value of 'MyStrongType' may not be empty." };
}
}
};
- Is this the correct approach using this library?
- Is there an alternative way (maybe I missed a modifier) to implement this kind of behaviour using this library?
- Is there an easy way to reuse something like this as a "NotEmpty" modifier?
Edit: After updating this question, I assume I've to look into the topic of custom modifiers.