[Development] Could support for C be added to Qt?
Kevin Kofler
kevin.kofler at chello.at
Sun Sep 11 16:49:45 CEST 2022
samuel ammonius wrote:
> What kind of human error would make converting between the
> pointers dangerous? I've never understood the point of C++
> making pointer types incompatible and then introducing templates
> to bypass this by making a new function for each pointer.
Templates in C++ are much more than hidden casts. (This is quite unlike the
Java generics which are really just syntactic sugar for using Object and
doing casts.) C++ templates really generate different code for different
instantiations, so you can also template on things that are not pointers at
all, you can even do some extent of "duck typing" in that you can call a
method by name and it will find it in the classes you instantiate the
template with, even if those classes do not derive from a common interface,
or the template instantiation will fail if the class has no such method.
(And if the failed declaration is a specialization, it will just silently
fall back to the more generic version, see SFINAE (specialization failure is
not an error), whereas if it is the only available declaration, you will of
course get a compile error if it fails to instantiate.) And through
specializations, you can make the templates do completely different things
for different types (and yes, you can simulate that with the C11 _Generic,
at least in the simple cases).
And in particular, C++ templates can catch type mismatches at compile time
(and even Java generics can do that to some extent), whereas pointer casts
do not catch any mismatch, they just trust you that the type you are casting
to makes sense.
> (I don't see why not use a macro with static casts instead of a
> template though. It would probably double the compile speed, and
> there's no practical way that a human error would happen.)
See above. I could see replacing a Java generic with a macro, at the expense
of type safety, and of course with the issue that Java is normally not run
through a preprocessor, but you cannot in general do that with C++ templates
(also because _Generic is typically *not* available in C++, but it would not
be a full replacement for everything you can do through template
metaprogramming anyway).
Kevin Kofler
More information about the Development
mailing list