【问题标题】:C++17 separate explicit method template instantiation declaration and definitionC++17 分离显式方法模板实例化声明和定义
【发布时间】:2026-01-31 14:55:01
【问题描述】:

我目前正在使用单独的显式类模板实例化声明和显式类模板实例化定义,以减少编译时间,并且效果很好。

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

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

谢谢。

类模板(工作):

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>;

a.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>;

【问题讨论】:

    标签: c++ c++17


    【解决方案1】:

    是的。

    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);
    

    【讨论】: