Code Yarns ‍👨‍💻
Tech Blog ❖ Personal Blog

C++: Template Separation Model

📅 2007-Jul-18 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, template ⬩ 📚 Archive

C++ function templates are a great way to reduce the amount of repeated code written to do the same operations on objects of different types. For example, a minimum function that handles any type could be written as:

template <typename T>
T min(T a, T b)
    return (a > b) ? b : a;

There are 2 ways to organize the template code: inclusion model and separation model. In the inclusion model, the complete function definition is included in the header file. In the separation model, the function declaration is in the header file and the function definition is put in the source file. However, it won’t work as expected. The keyword export needs to be used with the function definition (i.e., export template <typename T> …)

Though this is Standard C++, this won’t work! Welcome to the real world of C++. No major compiler out there supports this clean separation model (export keyword). Even the latest VC++ 8 doesnot support it. Nor does gcc.


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 • 📧