by chadzawistowski · 10y ago · 0 comments
Further support for the idea that C++ templates are an automated copy+paste mechanism is that you're allowed to give templates arguments that are not types.
Further reading: https://msdn.microsoft.com/en-us/library/c6cyy67b.aspx
C# type checks imply a performance hit and are an implementation detail. Nothing prevents a C# compiler to choose another one. It has nothing to do with generics vs templates.
For example Modula-3 and Ada compilers use the same approach as C++ for code generation of their generics.
So where is that example of something that can only be written with C# generics, but not with C++ templates?
A github gist maybe?
That is what enable_if, type traits, if constexpr and eventually concepts allow for.
#include <string>
template <typename T>
void foo(const T& arg) {
int x = std::string("int expected");
}
$ g++ -c template.cpp
$ // see, no error
Templates are only syntax-checked. The type checker is not even executed on the non-generic code inside of templates. The type checker will be executed after the template is instantiated (expanded). At that point, generic types do not exist. There exist only concrete types.By not doing runtime checks you get to skip that work at runtime, obviously, but you also get to enable other optimizations like inlining the monomorphised version.