[英]How to test if a class satisfies a concept in C++?
In rust one explicitly types impl Trait for Object
which guarantees that Object
will have this trait.在 rust 中,一个显式类型
impl Trait for Object
保证Object
将具有此特征。 Now C++20 concepts are of course a bit more general as they are not associated to just one type but possibly multiple types.现在C++20 的概念当然更通用一些,因为它们不仅仅与一种类型相关联,而且可能与多种类型相关联。 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.现在的概念有点像鸭子,如果你的 object 满足有人在
requires
块中尝试用它做的所有事情(它像鸭子一样嘎嘎叫),那么它会像鸭子一样通过并满足这个概念。 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?这样的一个是否
satisfies
function 存在,如果不存在:关于编写这样一个satisfies
function 的 go 怎么可能?
Ducktyping might not be enough if you pass your object to a library where implementation of certain concepts is optional (eg 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).如果您将 object 传递给一个库,其中某些概念的实现是可选的(例如,一个库接受可能位于或可能不位于边界的组件并且只对位于边界的对象执行某些计算),那么 Ducktyping 可能还不够。
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.
如果出现合理的数据,它甚至可能不会被检测到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.