c**********e 发帖数: 2007 | 1 1. Is the C++ template parameters decided at the compiling time or running
time?
2. How do you know the C++ template parameters are decided at the compiling
time or running time?
1 is simple. But how to answer 2? Thanks a ton. |
i**********e 发帖数: 1145 | 2 2. You can run some simple tests. By increasing the number of different
types being called to a function of generic type, you should notice the
binary file being larger, due to extra code being generated by the compiler
(for each of the type used). Haven't verified this myself yet, so if I'm
wrong please feel free to correct. |
s******n 发帖数: 3946 | 3 编译成汇编,每个method都有独立的signature |
h*****f 发帖数: 248 | 4 1. Compile time because template initialization is done during the compile
time and the initialization is based on the "known" template parameter(s)
during the compile time.
2. A way to prove:
#include
#include
template class Buffer {
char internal[max];
public:
void printSize() {
printf("buffer size=%lu\n", sizeof(internal));
}
};
int main() {
Buffer<512> my512;
my512.printSize();
size_t v;
std::cin >> v;
printf("my input=%lu\n", v);
/* Compilation error because tmeplate is generated in the compilation time,
and so a template cannot take a runtime value as the parameter
Buffer myInput;
myInput.printSize();
*/
return 0;
} |