C++17 单独的显式方法模板实例化声明和定义

C++17 separate explicit method template instantiation declaration and definition

本文关键字:实例化 声明 定义 方法 单独 C++17      更新时间:2023-10-16

我目前正在使用单独的显式类模板实例化声明和显式类模板实例化定义来减少编译时间,并且它运行良好。

但是,我有一些不是模板的类,而只是类中的一些方法。

是否可以对模板方法使用相同的单独声明和定义的机制?

谢谢。

类模板(工作(:

A.HPP :

template <class T>
class A {
    void f(T t);
};
// Class explicit template instantiation declaration
extern template class A<int>;
extern template class A<double>;

答.cpp:

template <class T>
void A<T>::f(T t) {
}
// Class explicit template instantiation definition
template class A<int>;
template class A<double>;

方法模板(不工作(:

b.hpp :

class B {
    template <class T>
    void g(T t);
};
// Method explicit template instantiation declaration
extern template method B::g<int>;
extern template method B::g<double>;

b.cpp:

template <class T>
void B::f(T t) {
}
// Method explicit template instantiation definition
template method B::g<int>;
template method B::g<double>;

是的。

b.hpp:

extern template void B::g(int);
extern template void B::g(double);

b.cpp:

template void B::g(int);
template void B::g(double);