如何理解这样的“两个连续模板”?在 c++通过使用模拟最小示例?
我只了解C++中一些简单的模板用法。
最近,我在一些 OpenFOAM 代码中遇到了以下代码片段,它让我困惑了好几个星期。
(1)您能否通过给出一个最小的工作示例来帮助我解释这种“两个连续模板”的用法?
(2) 是否可以将两个模板替换为单个模板,即template
哦,请忽略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
}
}
I only understan some simple template usage in C++.
Recently I met the following code snippet from some OpenFOAM code, and it confues me for weeks long.
(1) Could you please help me by giving a minimum working example to explain such "two consecutive templates" usage?
(2) Can I just replace the two tempalte with single template, i.e., template<Type, Type2>
Oh, please ignore the unknown classes such as Foam, fvMatrix.
Thanks~
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在一个文件中定义成员模板时, 类模板。
一个常见的例子是模板类的复制赋值运算符。考虑代码
对于不同专业的副本作业,您必须这样做。第一个
template
属于类模板Foo
,第二个template
属于复制赋值运算符,它是一个内部模板。对于第二个问题,答案是否。一个模板参数列表只能引入一个模板。这里有两个模板。第二类模板
Foam::fvMatrix
与模板参数T2
无关。 (对于那些对源代码感兴趣的人,请参阅 标头 和 实现)旁白:本主题5.5.1 节中介绍了C++ 模板:完整指南。
It's when you define a member template in a class template.
A common example will be a
copy assignment operator
for a template class. Consider the codeFor copy assignments from different specializations, you have to do this. The first
template <typename T>
belongs to the class templateFoo
, and the secondtemplate <typename U>
belongs to the copy assignment operator, it's an inner template.For your second question, the answer is No. One template parameter list can only introduce one template. There are two templates here. The second class template
Foam::fvMatrix
is of no business with template parameterT2
. (For those who are interested in source code, see header and implementation)Aside: this topic is covered in the 5.5.1 section of C++ Templates: The Complete Guide.