> Although guarded methods seem necessary, unfortunately, I don’t know of any mainstream languages that allow their definition.

C++ has this feature. When you define a template class, you can use SFINAE (or, in modern C++, concepts) to make it so that certain methods only exist if the template parameter meets certain requirements.

(Though even this is often unnecessary - for something like your `flatten` example, you could just go ahead and define it unrestricted. Methods of template classes are typechecked lazily - in other words, they don't need to successfully typecheck unless they're called. For this specific use case, SFINAE/concepts would just make the error message nicer.)

Rust also has this feature, with conditional impls.

> Rust also has this feature, with conditional impls.

Rust's approach seems more similar to the approach described in the section on extension methods, which the author admits solves the problem but doesn't like the implications for encapsulation (which isn't a problem in Rust, as long as you're writing this method in the same crate as the type definition). But Rust also doesn't have classic Java-style classes, so the requirement to "keep the member definition within the class" is already meaningless in Rust terms.

Idiomatically Rust explicitly prefers to make a type more generic, for example it's fine to talk about a HashMap<Goose,String> for some arbitrary user defined type Goose with no traits, and Rust will even cheerfully make you one... but you can't put any key+value pairs into that hash map because Goose isn't Eq [or Hash] so all the APIs for actually inserting or modifying the data don't exist on this type.

In contrast C++ won't even let you have std::unordered_map<Goose,int> because it wants to know how to compare and hash the keys before making the type at all.