我只了解 C 中一些簡單的模板用法。
最近我從一些 OpenFOAM 代碼中遇到了以下代碼片段,這讓我困惑了好幾個星期。
(1)您能否通過一個最小的作業示例來幫助我解釋這種“兩個連續模板”的用法?
(2)我可以用單個模板替換兩個模板嗎,即template<Type, Type2>
哦,請忽略 Foam、fvMatrix 等未知類。
謝謝~
template<class Type>
template<class Type2>
void Foam::fvMatrix<Type>::addToInternalField
(
const labelUList& addr,
const Field<Type2>& pf,
Field<Type2>& intf
) const
{
if (addr.size() != pf.size())
{
FatalErrorInFunction
<< "addressing (" << addr.size()
<< ") and field (" << pf.size() << ") are different sizes" << endl
<< abort(FatalError);
}
forAll(addr, facei)
{
intf[addr[facei]] = pf[facei];//intf是diag
}
}
uj5u.com熱心網友回復:
當您在類模板中定義成員模板時。
一個常見的例子是copy assignment operator模板類。考慮代碼
template <typename T>
class Foo {
// Foo& operator= (const Foo&); // can only be assigned from the current specilization
template <typename U>
Foo& operator= (const Foo<U>&); // can be assigned from any other specilizations
};
// definition
template <typename T>
template <typename U>
Foo<T>& Foo<T>::operator= (const Foo<U>&) {
...
}
對于來自不同專業的復制作業,您必須這樣做。第一個template <typename T>屬于類模板Foo,第二個template <typename U>屬于復制賦值運算子,它是一個內部模板。
對于您的第二個問題,答案是否定的。一個模板引數串列只能引入一個模板。這里有兩個模板。第二類模板Foam::fvMatrix與模板引數無關T2。(對原始碼感興趣的可以看頭檔案和實作)
另外:這個主題在C Templates: The Complete Guide的 5.5.1 部分中有介紹。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438908.html
