|
Boost : |
Subject: [boost] Feedback request for Invariant Library idea
From: Attila Szenczi (melkonka_at_[hidden])
Date: 2017-03-17 08:17:45
Hello!
I am asking for some feedback if my library idea is good enough to be part
of boost if it will meet the requirements.
When i started this small utility lib i had 3 goals in my mind:
- Write cleaner interfaces
- Be safer with pre and post conditions
- Eliminate redundant checks whenever possible at compile time
The goal is to solve this problem for primitive types.
*Example "bad" code:*
void set_red_color(int red) {
//Why the precondition is not visible on the interface?
assert(red >= 0 && red <= 255);
}
*Example "good" code:*
void set_red_color(bounded_i<0, 255> red) {}
*Example "bad" code:*
void foo(int bar) {
assert(bar >= 0);
}
*Example "good" code:*
void foo(positive_i bar) {}
or
void foo(lower_bounded_i<0> bar) {}
Basically the main idea is to have an invariant_host class, which is
customizable via policies:
-* Invariant policy:* Define a static check() function which ensure the
invariant.
- *Fail policy: *Define a static trigger_assert function which is called
when the invariant policy::check is failed.
If the fail policy is disabled (constexpr bool flag), then the checks
doesn't happen.
Defining your own class looks like this:
template<typename PrimitiveType>
using my_type = invariant_host<PrimitiveType, default_fail,
my_invariant<PrimitiveType>>;
*Optimizations:*
bounded_i<0, 50> bi (30); //trigger check
bounded_i<0, 100> bi2(bi); //range check happens at compile time
bounded_i<51, 52> bi3(bi1); //should be compile error
bounded_i<0, 50> bi4(integral_constant<int, 10>); //check should happen
compile time
Things like operator+,-,*,/, bitwise operators etc can trigger checks.
Tho alot of times it can be optimized away. For example adding 2 positive
number should stay positive.
C++20(?) contracts will be great, it will allow us to write cleaner
interfaces, but i don't feel like it solve every issue i would like to
solve.
Do you think it would be a good addition to boost? I appreciate any
feedback!
Thank you very much!
Attila Szenczi
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk