Main Content

AUTOSAR C++14 Rule A14-5-2

Class members that are not dependent on template class parameters should be defined in a separate base class

Description

Rule Definition

Class members that are not dependent on template class parameters should be defined in a separate base class.

Rationale

To access a member of a template class, you have to instantiate the template. If the member is not dependent on the template parameter, this instantiation step is not necessary. For instance, the members anotherMember and someotherMember of this template class aClass do not depend on the parameter T:

template <typename T>
class aClass {
   T aMember
   int anotherMember;
   int someotherMember
}
However, to access these members, you have to instantiate the template class aClass. To avoid the unnecessary template instantiation, do not include these members in the template declaration.

Including this member in the template declaration also causes unnecessary code bloat. Compilers generate a separate copy of a template class for each instantiation of a template. If a class member is not dependent on the template parameter, an identical copy of this member is created for each template instantiation.

Polyspace Implementation

The checker flags data members of template classes that are not dependent on template parameters. The checker does not flag member functions.

If multiple data members of a template are flagged by this checker, create a base class for the template that aggregates these data members.

In some cases, you might not want to strictly adhere to this rule. For instance, if only a single member of the template class is not dependent on the template parameter, you might not want to create a separate base class for this member. If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>

template <typename T> 
class aDataArray {
    T data[100];
    int32_t metadata[2]; //Noncompliant 
    int32_t info;        //Noncompliant
};

class metadataArray {
    int32_t metadata[2];
    int32_t info;
};

template <typename T> 
class anotherDataArray: public metadataArray { //Compliant
    T data[100];
};

In this example, the template class aDataArray includes data members metadata and info that are not dependent on the type parameter of the template, T. The template class anotherDataArray avoids the unnecessary instantiation. This class is derived from a base class metadataArray, which aggregates data members that are not dependent on a type.

Check Information

Group: Templates
Category: Advisory, Partially automated