Home > Enterprise >  How to understand such "two consecutive templates" in c by using a mimic minimum example
How to understand such "two consecutive templates" in c by using a mimic minimum example

Time:03-03

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

CodePudding user response:

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 code

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>&) {
    ...
}

For copy assignments from different specializations, you have to do this. The first template <typename T> belongs to the class template Foo, and the second template <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 parameter T2. (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.

  • Related