| ▲ | Almondsetat a day ago | |
>Suppose your function doodle_widget is supposed to take a Gonzo Widget, but you're worried somebody might call it with a Non-Gonzo Widget and that can't work. Can't you just use concepts? | ||
| ▲ | tialaramex a day ago | parent | next [-] | |
No. Bjarne's C++ 20 Concepts are basically duck typing, you can express that you want a type where we can call the "is_gonzo" function but you can't say that you only want values of that type in which it's true. Obviously you could re-design the software to follow a Rust-style type-state paradigm, have a NonGonzoWidget and GonzoWidget type which both inherit from Widget and now you can have your function take a GonzoWidget - but that's not what my comparison was about and this technique while possible is less common in C++ Edited to add: Actually, I should clarify that concepts have an idea called "modelling" and you can model anything you want, but the problem is that the machine doesn't care. So you can have a concept which models strings being about how awesome Donald Trump is, and the compiler won't and can't check that, but now a C++ program with a string matching that concept and the value "Trump is a moron" is an invalid C++ program, still compiles, still probably works, but your concept wasn't "modelled" so the program was not valid for whatever that's worth.... | ||
| ▲ | jandrewrogers a day ago | parent | prev [-] | |
Yes, these types of scenarios are commonly handled with C++20 concepts. The main thing contracts do is provide a standardized scaffolding for enforcement. | ||