Search code examples
c++templatescomparisonfunction-parameter

Which approach is better for supplying compile time constants to a function ? Function argument vs. Template parameter


I have logging function being called at several places throughout the code. To every log, I have to supply 2 compile time constants. There are 2 approaches to accomplish:

(1) Function argument:

template<typename T>
void log (const T &obj, const int LINE, const int COUNT)
{
  // T is used for some purpose
  if(debug)
    logging(obj.out(), LINE, COUNT);
}

call it as,

log(str, __LINE__, __COUNTER__);

(2) Template parameter:

template<typename T, int LINE, int COUNT>
void log (T &obj)
{
  // T is used for some purpose
  if(debug)
    logging(obj.out(), LINE, COUNT);
}

call it as,

log<__LINE__, __COUNTER__>(str);

I am not able to decide, because 1st approach offers simplicity, but we are passing constant at compile time. 2nd approach is perfect, but compilation time would probably increase. This task is tedious, and I haven't implemented any of them yet, so I don't have any bench mark.

It will be a great help if someone can answer this from their experience/knowledge.


Solution

  • I would go with the first option. The performance impact of passing two integers is negligible. The optimizer will also probably inline the function call in which case there would be no difference between the two. The second option I think is a bad idea, since you will be creating a lot of versions of the same function, for no reason.