问题
Is Warning 1573 ("Name of generic function template declared in namespace associated with type") really relevant when the namespace is an anonymous namespace? Most of the helper functions I have for tests go in unnamed namespace and it breaks the above rule.
Example:
namespace
{
template <typename T>
T template_func(T arg)
{
return arg;
}
class foo {};
}
int main()
{
return template_func(0);
}
How do I get around in the above, to satisfy the rule?
回答1:
As state in their example, you might use extra namespace, something like:
namespace
{
template< class T >
T template_func(T arg) { return arg; }
namespace X
{
class foo{};
}
using X::foo;
}
int main()
{
return template_func(0);
}
回答2:
I'd guess that it isn't aimed at polluting global namespace but to avoid class picking up weird matches from generic templates belonging to the same namespace.
It goes along the cpp core guideline T.47: Avoid highly visible unconstrained templates with common names
Specifically:
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.
As for how to bypass it, Jarod42 was 1st with an example in his answer.
来源:https://stackoverflow.com/questions/47039834/misra-c-rule-14-5-1-name-of-generic-function-template-declared-in-namespace-a