In rust one explicitly types impl Trait for Object
which guarantees that Object
will have this trait. Now C++20 concepts are of course a bit more general as they are not associated to just one type but possibly multiple types. Nevertheless this begs the question how one would go about veryfing that some type(s) you implemented actually satisfy some concept.
Right now concepts are a bit duck-typish, if your object satisfies all the things someone tried to do with it in a requires
block (it quacks like a duck), then it passes as a duck and satisfies the concept. But is there a way to say: "I want this assortment of classes to pass the test"?
This could look like this for example:
class MyClass1 { ... }
class MyClass2 { ... }
template<typename T1, T2>
concept MyConcept = requires(T1 t1, T2 t2) { ... }
static_assert( satisfies<MyConcept, MyClass1, MyClass2>() )
Does such a satisfies
function exist, and if not: how could one go about writing such a satisfies
function?
Some Motivation
Ducktyping might not be enough if you pass your object to a library where implementation of certain concepts is optional (e.g. a library accepting components which might or might not be located at a border and only performs certain calculations for objects located at the border).
template <typename GeneralComponent>
void do_something_optionally(GeneralComponent component) {
if constexpr ( satisfies<isBorder, GeneralComponent>() ) {
do_border_calculation(component);
} else {
// don't do border calculation
}
}
do_border_calculation(isBorder auto& parameter);
It would then be very annoying to figure out why this library does not think you satisfy some concept. It might not even be detected if plausible data comes out.
static_assert(MyConcept<MyClass1, MyClass2>);
? – Holohedral