Suppose you have multiple implementations of the same interface and want to make sure that all of them satisfy some common requirements.
If you are designing an interface or concept, you can define a suite of type-parameterized tests to verify properties that any valid implementation of the interface/concept should have. Then, the author of each implementation can just instantiate the test suite with their type to verify that it conforms to the requirements, without having to write similar tests repeatedly. Here’s an example ...
Ad-hoc solution in Rust could be:
File with trait:
pub trait Sensor {
fn new(id: i32, path: &str) -> Self;
fn id(&self) -> i32;
...
}
mod tests {
// A test for the id() getter that any implementation should satisfy:
pub fn id_can_be_fetched<T: Sensor>() {
let sensor = T::new(1234, "asdf");
assert_eq!(sensor.id(), 1234);
}
}
Rust's test harness doesn't have anything like this built in, and we don't have any fancy reflection mechanisms which would let you automatically discover trait implementations or dynamically create tests on the fly. You'd probably have to write your own abstractions for a "generic test suite" that can be instantiated with different types, possibly using a macro to generate individual tests like id_can_be_fetched() (I could see some sort of custom attribute for traits coming in handy here).
How would you implement this in C++? Maybe you can take some inspiration from that.
I guess at this point, some sort of type-erasure happens, and all the provided types/objects get wrapped into callable objects/lambdas, which can then be stored in another static array and called at run-time.