Reputation: 21
Is is possible to make something like this:
class Tag1;
class Tag2;
template <typename Tag>
void foo(){}
void bar()
{
//here I nee to know how many times I have referenced foo<Tag1> and foo<Tag2>
//code chunk
//...
foo<Tag1>();
//another code chunk
foo<Tag2>();
//much more of code and calls of foo
...
}
I need to make some progress bar on huge calculations.
p.s. I need to know it at compile time. Foo is not required to be function, it can be object but not a macro.
Upvotes: 1
Views: 223
Reputation: 1334
We can use typeid and a map to keep track of type of objects created.
#include <iostream>
#include <string>
#include <typeinfo>
#include <map>
#include <algorithm>
using namespace std;
class Tag1{};
class Tag2{};
map<string, int> typeCountMap;
void getTypeCount(const string& tagname)
{
map<string, int>::iterator itr = typeCountMap.find(tagname);
if(itr != typeCountMap.end())
typeCountMap[tagname] += 1;
else
typeCountMap[tagname] = 1;
}
template <typename Tag>
void foo(){
getTypeCount(typeid(Tag).name());
}
void bar()
{
//here I nee to know how many times I have referenced foo<Tag1> and foo<Tag2>
//code chunk
//...
foo<Tag1>();
//another code chunk
foo<Tag2>();
//much more of code and calls of foo
//...
}
void print(const pair<std::string, int>& entry)
{
cout<<"type ["<<entry.first<<"] value ["<<entry.second<<"]"<<endl;
}
int main()
{
bar();
bar();
bar();
foo<Tag2>();
for_each(typeCountMap.begin(), typeCountMap.end(), print);
return 0;
}
/*
output
type [4Tag1] value [3]
type [4Tag2] value [4]
*/
Upvotes: 0
Reputation:
If you want to count each tag separately then you simply create a static variable and increment it:
template <typename Tag>
void foo() {
static int x = 0;
++x;
// ...
}
Upvotes: 1