Automatically count the number of instantiated classes in a TMP?

不问归期 提交于 2019-11-28 08:33:33

I made a one-line change to GCC that makes it print out the name of each class template as it instantiates it. You can already call the C++ front-end cc1plus directly without the -quiet flag to get the same for function templates.

I haven't got round to turning that into a proper GCC option yet, it's just a hack on my own source tree. I'm thinking of implementing it as a plugin instead, but it's not near the top of my TODO list.

There is, of course, no portable way to do this.

There are hacky ways to do it for most compilers. You already found one for MSVC. For gcc, you can probably use gccxml. Or, for any open source compiler (gcc or clang), it should be pretty simple to add code at the point of instantiation that either keeps count, or logs something that you can filter after the compile is done.

For Clang/LLVM, you can just build a plugin that hooks the instantiation, which is a lot cleaner, but probably actually more work.

A build with debug symbols, no optimization, and no stripping might end up with the mangled names of every instantiation, which you can grep for. However, some compilers (including gcc) will always inline at least some methods, whether you want them to or not. If you're willing to modify your code, you can probably force it to generate out-of-line instantiations, maybe something like this:

template<int N> struct fact { 
  enum { value = N * fact<N-1>::value }; 
  int *dummy() { return &fact<N-1>::value; }
};

There is a tool written by Steven Watanabe that can be used to count the number of template instantiations. You can get it here. Basically, it modifies the code so that a compiler warning is generated every time a class is instantiated and you can then process the resulting text with regexes, for instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!