Main Content

AUTOSAR C++14 Rule A5-1-7

A lambda shall not be an operand to decltype or typeid

Description

Rule Definition

A lambda shall not be an operand to decltype or typeid.

Rationale

According to the C++ Standard, the type of a lambda expression is a unique, unnamed class type. Because the type is unique, another variable or expression cannot have the same type. Use of decltype or typeid on a lambda expression indicates that you expect a second variable or expression to have the same type as the operand lambda expression.

Both decltype and typeid return the data type of their operands. Typically the operators are used to:

  • Assign a type to another variable. For instance:

    decltype(var1) var2;
    creates a variable var2 with the same type as var1.

  • Compare the types of two variables. For instance:

    (typeid(var1) == typeid(var2))
    compares the types of var1 and var2.

These uses do not apply to a lambda expression, which has a unique type.

Polyspace Implementation

The rule checker flags uses of decltype and typeid with lambda expressions.

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>
#include <typeinfo>
 
 void func()
 {
 auto lambdaFirst = []() -> std::int8_t { return 1; };
 auto lambdaSecond = []() -> std::int8_t { return 1; };

 if (typeid(lambdaFirst) == typeid(lambdaSecond))  
     {
     // ...
     }
 }

The use of typeid on lambda expressions can lead to unexpected results. The comparison above is false even though lambdaFirst and lambdaSecond appear to have the same body.

Correction – Assign Lambda Expression to Function Object Before Using typeid

One possible correction is to assign the lambda expression to a function object and then use the typeid operator on the function objects for comparison.

#include <cstdint>
#include <functional>
#include <typeinfo>

 void func()
 {
 std::function<std::int8_t()> functionFirst = []() { return 1; };
 std::function<std::int8_t()> functionSecond = []() { return 1; };

 if (typeid(functionFirst) == typeid(functionSecond)) 
     {
     // ...
     }
 }

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019b

expand all