Forcing the compiler to generate code for all member functions of a template class?

China☆狼群 提交于 2020-12-10 05:51:02

问题


Say I have this program

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

int main() {
  A<int> a;
  a.foo();
  return 0;
}

Both g++ and clang++ only generate code for A<int>::foo(), but not for A<int>::bar(). This is annoying when you want to call this function while debugging. (e.g. vector<T>::at() ).

Is there some flag or other method by which you can force the generation of code for all member functions every time a template is instantiated?


回答1:


No compiler flags, but the rules of the language govern what is happening here, and you can use them to your advantage.

Since you are implicitly instantiating A<int>, only the functions you use are instantiated:

[C++11: 14.7.1/1]: [..] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates; [..]

If you explicitly instantiate A<int>, instead, then the whole thing gets instantiated.

#include <iostream>

using namespace std;

template<typename T>
class A {
public:
    void foo() { cout << "Inside foo" << endl; }
    void bar() { cout << "Inside bar" << endl; }
};

template class A<int>;   // <----

int main() {
  A<int> a;
  a.foo();
}

Here is some proof: http://coliru.stacked-crooked.com/a/582126aac45d6ea4




回答2:


Explicitly instantiate it:

template class A<int>;



回答3:


Aside what other's said about template instantiation, you might find useful to declare some functions/methods as 'used', to prevent the optimizers from removing them if they seem unused.

http://gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc/Function-Attributes.html

see attribute used



来源:https://stackoverflow.com/questions/21166762/forcing-the-compiler-to-generate-code-for-all-member-functions-of-a-template-cla

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