MISRA C++ 规则 14-5-1:在与类型关联的命名空间中声明的通用函数模板的名称

MISRA C++ Rule 14-5-1: Name of generic function template declared in namespace associated with type

警告 1573 ("Name of generic function template declared in namespace associated with type") 在名称空间是 匿名命名空间?我用于测试的大部分辅助函数都在未命名的命名空间中,它违反了上述规则。

示例:

namespace
{
  template <typename T>
  T template_func(T arg)
  {
    return arg;
  }

  class foo {};
}

int main()
{
  return template_func(0);
}

我如何解决上述问题以满足规则?

如示例中所述,您可以使用额外的命名空间,例如:

namespace
{
    template< class T >
    T template_func(T arg) { return arg; }

    namespace X
    {
        class foo{};
    }
    using X::foo;
}

int main()
{
    return template_func(0);
}

我猜它不是为了污染全局命名空间,而是为了避免 class 从属于同一命名空间的通用模板中挑选奇怪的匹配项。

它遵循 cpp 核心指南 T.47: Avoid highly visible unconstrained templates with common names

具体来说:

Reason : An unconstrained template argument is a perfect match for anything so such a template can be preferred over more specific types that require minor conversions. This is particularly annoying/dangerous when ADL is used. Common names make this problem more likely.

Note: If an unconstrained template is defined in the same namespace as a type, that unconstrained template can be found by ADL (as happened in the example). That is, it is highly visible.

至于如何绕过,Jarod42 was 1st with an example in his