Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用显式模板实例化来减少编译时间?_C++_Templates_Compilation - Fatal编程技术网

C++ 如何使用显式模板实例化来减少编译时间?

C++ 如何使用显式模板实例化来减少编译时间?,c++,templates,compilation,C++,Templates,Compilation,建议使用显式模板实例化来减少编译时间。我想知道怎么做。比如说 // a.h template<typename T> class A {...}; template class A<int>; // explicit template instantiation to reduce compilation time //a.h 模板类A{…}; 模板类别A;//显式模板实例化以减少编译时间 但在每个包含a.h的翻译单元中,似乎都会编译a。编译时间没有减少。如何使用显

建议使用显式模板实例化来减少编译时间。我想知道怎么做。比如说

// a.h
template<typename T> class A {...};
template class A<int>; // explicit template instantiation  to reduce compilation time
//a.h
模板类A{…};
模板类别A;//显式模板实例化以减少编译时间

但在每个包含a.h的翻译单元中,似乎都会编译
a
。编译时间没有减少。如何使用显式模板实例化来减少编译时间?

在标题中声明实例化:

extern template class A<int>;
extern模板A类;
并在一个源文件中定义它:

template class A<int>;
A类模板;

现在它将只实例化一次,而不是在每个翻译单元中实例化,这可能会加快速度。

如果您知道您的模板将仅用于某些类型, 让我们称它们为T1,T2,您可以将实现移动到源文件, 像普通班一样

//foo.hpp
template<typename T>
struct Foo {
    void f();
};

//foo.cpp
template<typename T>
void Foo<T>::f() {}

template class Foo<T1>;
template class Foo<T2>;
//foo.hpp
模板
结构Foo{
无效f();
};
//foo.cpp
模板
void Foo::f(){}
模板类Foo;
模板类Foo;

Cool不知道这一点,它将使用显式模板实例化定义指令(
template class A;
)在所有源文件中实例化。@Constructor:确实如此。如果你按照答案所说的去做,那只会发生一次。我只想指出,显式模板实例化声明并不能很好地保护一个模板的多个实例化(意外的或有意的)。你能给我一个提示,说明如何很好地保护它吗?有吗?我通常使用两个头文件——一个保存模板代码,另一个包含第一个并且只包含“extern template”显式规范化声明。然后一个源文件包含第一个,显式声明和所有其他源文件都包含第二个和“extern template”声明。实现的形式不应该是
template void Foo::f(){}
?注意
Foo::
而不是
Foo::