Search code examples
c++creationfunction-template

How/where are template-functions allocated?


Is the following use of the template-function fCompare() correct?

//header

template<typename _T > class SomeClass
{
    typedef int (*COMPAREFUNC)(_T*,_T*);
    COMPAREFUNC Compare;
public:
    void SetCompareFunction(COMPAREFUNC pfC) { Compare=pfC; }
    ...
};

template<typename _T > int fCompare(_T *pO, _T *pN)
{
    if (pN==NULL) throw (const char*)"Null not allowed";
    if (pO!=NULL) return (*pO > *pN)?1:(*pO < *pN)?(-1):0;
    return 0;
}

//code

    SomeClass<int> aC;

    aC.SetCompareFunction(fCompare<int>); //                <******* here
    ...   

My worry is where the instance function is created from the template: it looks like the stack, but in other code I used to test it, I tried to hammer the stack, and the Compare() just kept on going. Can I safely use the template like this?


Solution

  • fCompare<int> is created at compile time, as part of the code segment. You can think of it as a sort of constant, static data, just like a const int at file scope would be. Each time you invoke SetCompareFunction, therefore, it receives a pointer to the same function. Thus, no matter how many times you invoke it, it won't use up any extra memory, and you won't run out of stack or heap space just from doing so.

    The corollary to this is that template function arguments must always be something that can be computed at compile time. It's illegal to pass in a variable (except for a template variable) as a template parameter.