Friday 16 August 2019

c++ - Explicit instantiation of class template not instantiating constructor



I'm working on a project in C++ and am having trouble understanding what members of a template class get explicitly instantiated when I explicitly instantiate the template class. I've written the following file, which I then compile using Visual C++ 2008 Express Edition's Release configuration and then pop into a disassembler.



template class test {
public:
template test(T param) {

parameter = param;
};
~test() {};
int pop();
int push();
T parameter;
};

template int test::push() {return 1;}
template int test::pop() {return 2;}


template class test;

int main() {
return 0;
}


Ignoring that this file doesn't really need templates for the moment, this compiles fine. I throw the exe into the disassembler and it tells me that test::pop(void), test::push(void), and test::~test(void) are functions in the exe, but I don't see the constructor. I know I can explicitly instantiate the constructor with




template test::test(int);


which causes test::test(int) to appear in the disassembly as a function with the other ones. My understanding of explicit instantiation is that it is supposed to tell the compiler to instantiate all members of a template class for a given set of arguments, so why is it that the constructor is not explicitly instantiated along with all the other member functions?


Answer



When the constructor is a template member function, they are not instantiated unless explicitly used.



You would see the code for the constructor if you make it a non-template member function.



template class test {

public:

/***
template test(T param) {
parameter = param;
};
***/

test(T param) : parameter(param) {}
~test() {}

int pop();
int push();
T parameter;
};

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...