slashmais
slashmais

Reputation: 7155

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?

Upvotes: 0

Views: 76

Answers (2)

bdonlan
bdonlan

Reputation: 231363

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.

Upvotes: 1

Nick
Nick

Reputation: 6846

As far as I can tell, yes. Expanded template functions are the same as normal functions; in your example, fCompare<int> would be the same as an independent function called fCompare_int, with int substituted for the template parameter. Since you're effectively just taking the address in the function call, all is good.

Upvotes: 1

Related Questions