我对模板的概念有点困惑。也就是说,如果你有这样的功能:
template<typename T>
void DoubleValue(T ¶m)
{
param *= 2;
}
编译器如何知道我可以将哪些类型传递给此函数?如果代码适用于该类型,它会测试所有已知类型吗?这有性能问题吗?
最佳答案
与 Java 或 C# 中的泛型相反(类型参数的行为类似于 boost::any
,即编译器安全、运行时检查的 void*
), [类/函数]模板不是[类/函数]。它用于在实例化点(不要与对象实例化混淆)生成临时[类/函数]。
实例化可以是显式的:
// Hey compiler, please generate code for DoubleValue<int>.
template void DoubleValue<int>(int ¶m);
...或隐含的:
int main() {
// Hey compiler, I want to call DoubleValue<float>.
// Please generate the code if it's not done already.
return DoubleValue(1.5f);
}
所有这些都是在编译时完成的。
关于c++ - 使用模板时实际发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240520/