Does MISRA C++ Rule 14-5-1: (Do not declare a generic function in an associated namespace) apply for std::operator<<?

778 views Asked by At

MISRA C++ 2008, Rule 14-5-1 states that "A non-member generic function shall only be declared in a namespace that is not an associated namespace".

Considering the case of (e.g) overloading the operator<<(), I wonder if this is not the very case to avoid with the MISRA rule. Example:

#include <iostream>
std::ostream& operator<<(std::ostream &s, int x){    
   s << "my operator<<" << std::endl;
   return s;
}

int main() {
   std::cout << 5L << std::endl;
   return 0;
}

This results in not calling my output operator, but rather the STL output operator. So: is this an example of MISRA rule 14-5-1 violation where ADL picks the unintended function?

1

There are 1 answers

2
Jarod42 On

As I understand, that rule is to avoid that template (free) functions are used with ADL.

operator<<() doesn't apply, except maybe the following (because of T)

template<class charT, class traits, class T>
basic_ostream<charT,traits>&
operator<< (basic_ostream<charT,traits>&& os, const T& val);

but anyway, operator are mostly useless without ADL, or else we would have to import them before there usage (as we should do for UDL as operator ""s)

Better example would be std::begin which broke the rule:

std::vector<int> v;

begin(v); // -> std::begin(v)

I don't understand which errors that rule try to prevent.