If I define a function (maybe a class member function but not inlined) in a header file that is included by two different translation units I get a link error since that fun
This is implementation specific.
Some compilers will generate the same template instances over and over for each translation unit they are instantiated in and let the linker fold the duplicates.
Templates got a bad reputation for "code bloat" when linkers weren't yet up to that task. Nowadays this is probably undeserved. Some implementations will even fold different instantiations when they compile to the same target machine code. (Like f()
and f()
, as pointer types are just addresses in the generated machine code.)
Others will defer template compilation until link-time instead, and there might be still other ways to deal with this. As I said, it's up to the implementation.
These all have different advantages and disadvantages. Absent of a true module concept I doubt anyone will come up with the perfect scheme.
With export
there used to be a requirement for compilers to pre-compile template code and instantiate at request. However, except for one vendor nobody implemented export
for their compiler, and now it's removed.