不同头文件中的函数模板解释可以通过以下步骤进行解决:
// function_template.h
#ifndef FUNCTION_TEMPLATE_H
#define FUNCTION_TEMPLATE_H
template
T add(T a, T b) {
return a + b;
}
#endif // FUNCTION_TEMPLATE_H
// main.cpp
#include "function_template.h"
#include
int main() {
int a = 5, b = 10;
double c = 2.5, d = 3.7;
int result1 = add(a, b); // 使用函数模板,并指定模板参数类型为 int
double result2 = add(c, d); // 使用函数模板,并指定模板参数类型为 double
std::cout << "Result 1: " << result1 << std::endl;
std::cout << "Result 2: " << result2 << std::endl;
return 0;
}
在这个示例中,我们创建了一个名为function_template.h
的头文件,其中定义了一个函数模板add
。该函数模板可以接受任意类型的参数,并返回这些参数的和。在main.cpp
中,我们包含了function_template.h
头文件,并使用add
函数模板进行了两次计算,分别传入了整数和浮点数作为参数。最后,我们输出了计算结果。
注意:在使用函数模板时,可以显式指定模板参数类型(如add
)或者让编译器自动推断模板参数类型(如add(c, d)
)。