假设我在“Foo.h”文件中有一个模板静态类,如下所示:
template<typename T> class Foo
{
public:
static T foo1();
static T foo2();
static T foo3();
static T foo4();
static T foo5();
};
// definitions...
现在,假设我有一个这样的“main.cpp”文件:
#include "Foo.h"
main()
{
double value = Foo<double>::foo3();
// Do something with value
return 0;
}
当我编译这个文件时,方法 foo1()
、foo2()
、foo4()
和 foo5 ()
是否也在生成的代码中?
最佳答案
没有。
C++ Standard 14.7.1/10
An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. (...)
这是一种非常有用的技术,尤其是与基于策略的设计结合使用时。您基本上可以定义仅适用于某些模板参数的成员函数;如果在这种情况下不使用它们,就不会出现编译错误。
关于C++模板静态类代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22055403/