Dev Notes

Software Development Resources by David Egan.

C++ Namespace Template Functions


C++, Templates
David Egan

If you define a C++ template function in a namespace, the function definition needs to go in the header - not the .cpp file.

Example

// utilities.h
#include <vector>
#include <iostream>
#include "Employee.hpp"

namespace utilities
{
    // Function declaration - this function can be defined in utilities.cpp
    void employeesReport(std::vector<Employee> staff);

    // Template function must be defined in utilities.h
    template <typename T>
    void outputVec(const char * label, std::vector<T> collection)
    {
        std::cout << label << ": " << std::endl;;
        for(typename std::vector<T>::iterator it = begin(collection); it != end(collection); it++)
            std::cout << *it << (std::next(it) != collection.end() ? ", " : "");
        std::cout << std::endl;
    }
}

You could also put the implementation in .cpp and include this file from within the header file.

Why?

Template functions are not real functions - they are turned into a real function by the compiler when it encounters a use of the function.

This means that the template definition needs to be in the same scope as the call to the function. If the function is called in main.cpp and utilities.h is included in this file, then the template must be defined in utilities.h.

References

SO answer with good explanation


comments powered by Disqus