ritter
ritter

Reputation: 7699

How to count function template instantiations

Say I have a function template func and it gets instantiated several times with the same template parameter. The individual instances with the same template parameter should be counted (from 0 on) and the instance count should be accessible from func's implementation. Clearly, a static member is not what I am searching for. Instead, it looks to me that instance counting needs to be implemented with compile-time type computation.

Example (user code):

{
  for(int i=0;i<10;i++) {
    func<float>();           // This should be instance number 0
  }
  func<float>();             // This should be instance number 1
}

Despite the runtime loop the first instance of func gets the number 0. That is over all loop iterations the instance number should not change. Only when the loop exits and the function is called again, the number should be incremented, namely to 1.

Original template:

template<class T> void func() {}

Possible ways to access the instance count:

template<class T,int COUNT> void func() {}   // instance number as template parameter
template<class T> void func(int count) {}    // or as function argument

Can this be done with some fancy call wrapper? If so, how?

I fear it's not possible... But, right now I have a good use for it ..

Upvotes: 0

Views: 2031

Answers (3)

vonbrand
vonbrand

Reputation: 11791

What you explain in your comment is that you want to cache the function results. This is called memoization. You should perhaps create a full class to handle the function's memoization for each template argument.

If you expect the function to reduce to the same value each time, perhaps check first if the compiler does that by itself (g++ -S -g shouldn't be too unreadable...).

Upvotes: 0

Eric
Eric

Reputation: 97575

template<class T> class impl {
    template<int count>
    static void funcImpl() {}
}

#define func funcImpl<__COUNTER__>

...

impl<float>::func()

Upvotes: 0

thiton
thiton

Reputation: 36049

An instantiated function template is a function. Each function only exists once in your program. Therefore, you cannot count instantiations, because there is only a single instantiation of func<float>.

Upvotes: 3

Related Questions