如何通过使用模拟最小示例来理解 c++ 中的 "two consecutive templates"?
How to understand such "two consecutive templates" in c++ by using a mimic minimum example?
我只了解一些简单的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
}
}
当你定义一个member template in a class template.
一个常见的例子是 copy assignment operator
模板 class。考虑代码
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>
属于class模板Foo
,第二个template <typename U>
属于复制赋值运算符,是一个内部模板
对于你的第二个问题,答案是否。一个模板参数列表只能引入一个模板。这里有两个模板。第二个 class 模板 Foam::fvMatrix
与模板参数 T2
无关。 (有兴趣源码的可以看header and implementation)
旁白:C++ 模板:完整指南.
的 5.5.1 部分介绍了该主题
我只了解一些简单的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
}
}
当你定义一个member template in a class template.
一个常见的例子是 copy assignment operator
模板 class。考虑代码
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>
属于class模板Foo
,第二个template <typename U>
属于复制赋值运算符,是一个内部模板
对于你的第二个问题,答案是否。一个模板参数列表只能引入一个模板。这里有两个模板。第二个 class 模板 Foam::fvMatrix
与模板参数 T2
无关。 (有兴趣源码的可以看header and implementation)
旁白:C++ 模板:完整指南.
的 5.5.1 部分介绍了该主题