假设您template_function<T>()
在其他两个 .cpp 文件(a_uses_template.cpp
和b_uses_template.cpp
)中使用相同的内容,它们都隐式地实例化了模板。
据我了解,这应该会导致代码重复,因为a_uses_template.cpp
和b_uses_template.cpp
是单独编译的,所以template_function<T>()
会被实例化两次。
但是,如果我将代码更改为仅使用一个显式实例化,则生成的可执行文件会更大,而不是预期的更小。
这怎么可能?
主文件
#include <iostream>
#include "a_uses_template.h"
#include "b_uses_template.h"
int main() {
function_a_uses_template();
function_b_uses_template();
}
a_uses_template.h
#ifndef A_USES_TEMPLATE_H_
#define A_USES_TEMPLATE_H_
void function_a_uses_template();
#endif /* A_USES_TEMPLATE_H_ */
a_uses_template.cpp
#include <iostream>
#include "template_function.h"
#include "a_uses_template.h"
void function_a_uses_template() {
std::cout << "function_a_uses_template, template_function<int>(): "
<< template_function<int>() << std::endl;
}
以下是 template_function.h /.cpp 的两个变体,第一个 with 与两个隐式实例一起使用,然后是两个包含一个显式实例的文件。
template_function.h(具有两个隐式实例的变体)
#ifndef TEMPLATE_FUNCTION_H_
#define TEMPLATE_FUNCTION_H_
#include <cstddef>
template<typename T> size_t template_function() {
size_t s = sizeof(T);
// some code that the compiler won't erase during optimization
while (s != 1) {
if ((s & 1) == 0) {
s /= 2;
} else {
s = 3 * s + 1;
}
}
return s;
}
#endif /* TEMPLATE_FUNCTION_H_ */
template_function.h(具有一个显式实例化的变体)
#ifndef TEMPLATE_FUNCTION_H_
#define TEMPLATE_FUNCTION_H_
#include <cstddef>
template<typename T> size_t template_function();
#endif /* TEMPLATE_FUNCTION_H_ */
template_function.cpp(具有一个显式实例化的变体)
#include "template_function.h"
template<typename T> size_t template_function() {
size_t s = sizeof(T);
// some code that the compiler won't erase during optimization
while (s != 1) {
if ((s & 1) == 0) {
s /= 2;
} else {
s = 3 * s + 1;
}
}
return s;
}
template size_t template_function<int>(); // one explicit instanciation