0

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?

slashmais
  • 7,069
  • 9
  • 54
  • 80
  • 1
    I'm sorry, but what do you mean by "hammer the stack?" C++ templates typically are implemented by expanding out into normal functions, so they should behave as such. Without knowing what you did to try to destroy the program, I'm not sure how much I can help. – templatetypedef Mar 11 '12 at 05:34
  • @templatetypedef: I'm an ex-C-programmer, so anything that's passed as function-parameters goes on the stack .. not always so in C++, which makes me happy because this template-stuff really make coding a lot simpler. – slashmais Mar 11 '12 at 05:44
  • @slashmais that entirely depends on the implementation. –  Mar 11 '12 at 10:54
  • @daknok_t: yeah - I had a look at Boost & I'm nowhere near fully understanding all the tricks they 'commit' ;) – slashmais Mar 11 '12 at 12:54

2 Answers2

1

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.

Nick
  • 6,808
  • 1
  • 22
  • 34
1

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.

bdonlan
  • 224,562
  • 31
  • 268
  • 324