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?
A code for template function is generated when the function is instantiated. The functions are often instantiated when they are first time called (in the code), but there are other ways to instantiate a function - do a so-called 'explicit instantiation'.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.
Compiler creates a new instance of a template function for every data type. So compiler creates two functions in the above example, one for int and other for double. Every instance has its own copy of static variable. The int instance of function is called twice, so count is incremented for the second call.
Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With