[Repost] How to Organize Template Source Code

zhaozj2021-02-16  74

How to Organize Template Source Code

By Nemanja Trifunovic

Different Ways to Organize Source Code In C Template Libraries

Introduction

Often I get asked whether programming with templates is hard or easy The answer I usually give is:. "It is easy to use templates, but it is hard to make them" Just take a look at some template libraries that we use in our. Everyday Programming, Like STL, ATL, WTL, Some Libraries from Boost, And You Will See What Mean By. Those Libraries Are Great Example of The Princi "Simple Interface - Complex Implementation".

I started using templates five years ago when I discovered MFC template containers, and until last year I had no need to develop them myself. When I finally got to the point that I needed to develop some template classes, the first thing that hit me was the fact that the "traditional" way of organizing source code (declarations in * .h files, and definitions in * .cpp files) does not work with templates. It took me some time to understand why this is the case, and how to Work arround this problem.

This article is aimed at developers who understand templates well enough to use them, but are not very experienced at developing them. Here, I will cover only template classes and not template functions, but the principles are the same in both cases.

The Problem Described

To Illustrate The Problem, We Well Use An Example. Suppose We Have a Template Class Array (Nothing to Do With Boost :: Array Template Class) in A File Array.h.