我曾經按照https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl的建議來分離模板頭和實作。我們基本上在檔案末尾顯式實體化所需的模板,.cc以便編譯單元包含足夠的資訊供聯結器使用。
我最近了解到,我們只需要顯式實體化一個類建構式就可以創建一個實體。例如,
// .h file
template<typename T>
class A {
public:
A(T& t) : t_(t) {};
void PublicMethod();
private:
void PrivateMethod();
T& t_;
};
// .cc file
template<typename T>
void A<T>::PublicMethod() { PrivateMethod; return;}
template<typename T>
void A<T>::PrivateMethod() {
// Do some work.
return;
}
// Here I only instantiate the constructor and public interface.
template A::A(int);
template void A<int>::PublicMethod();
// In main, I can do following.
int main() {
A<int> a(2);
a.PublicMethod();
}
我不清楚的部分是:
- 如果我實體化公共方法,它是否也會自動實體化所有相關的私有方法?
uj5u.com熱心網友回復:
不,如果您顯式實體化一個成員(包括建構式),那么只有該成員的定義將被顯式實體化。
顯式實體化可能會導致類的其他成員的隱式實體化,但這還不足以在不同的翻譯單元中使用這些成員。如果您不打算在不同的翻譯單元中使用私有成員,那么顯式實體化公共/受保護的成員函式就足夠了。
如果要顯式實體化所有類成員,則應顯式實體化類模板特化本身:
template class A<int>;
template A::A(int);
這是不正確的。您的建構式需要一個參考,所以它應該是int&而不是int. 此外A是模板,而不是它的專業化。您必須指定專業化:
template A<int>::A(int);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/515587.html
標籤:C 模板
上一篇:C 生成可變數量的嵌套FOR回圈
