3 ms·
> Because whoever wrote foo () was too lazy to make use of type traits and validate that T has a method called bar with zero arguments. In a proper generic typ
by pkolaczk 11y ago
> Because whoever wrote foo () was too lazy to make use of type traits and validate that T has a method called bar with zero arguments.
In a proper generic type system, the compiler validates it, not the programmer. Even if you constrain the type using type traits, the compiler would not check if the implementation satisfies the constraints. I can put a type trait for existence of bar() and then another programmer may rename bar() to baz() forgetting to update the constraint and the code will still compile fine.
- pjmlp 11y agoExcept that reasoning fails with concepts, already available in GCC 6.0 and as a TS.
- pkolaczk 11y agoSo you're saying concepts will reject libraries that compile fine today?
- pjmlp 11y agoThey might, if used properly. I do admit that I need to update myself with what GCC 6.0 allows vs the letter of the TS.
- fauigerzigerk 11y agoI don't think concepts are even necessary to do what pkolaczk wants to do, which is (I think) to constrain the argument to a particular interface, say Bar: template <typename T> void foo(const T& arg) { const Bar* b = arg; b->bar(); } or template <typename T> void foo(const T& arg) { static_assert(is_base_of<Bar, T>::value, "T must be a Bar"); arg.bar(); } I can't say I'm a huge fan of either syntax, but the compiler will perform static type checking as if you had written where T : Bar in C#.
- pkolaczk 11y agoThe body of the template won't be typechecked until the instantiation of the template. This is different than in C#. If I replaced arg.bar with arg.baz in C#, the generic type definition would not compile, even if I never use it. In C++ I can't write a template and have it typechecked for all possible input types satisfying the type constraints, in C# I can. So C++ type system is weaker than that of C#.
- fauigerzigerk 11y agoI see what you mean, but uninstantiated also means unused. So we're not talking about anything that could possibly lead to runtime errors. It's not an issue with type safety. It definitely has a downside for the development process, especially when it comes to writing libraries. But it is also to some degree inevitable if you want structural typing. Maybe there is a better way to do it though.
- deleted 11y ago[deleted]