According to What are the reasons that extending the std namespace is considered undefined behavior?, adding anything to namespace std is Undefined Behavior, with some exceptions carved out, such as specializing std::hash. The primary reason for this is to allow the namespace to grow in future standards without risking collisions with user-written code.
Therefore, is it allowed to backport a specific feature to older standards, provided there are no language restrictions forbidding it? It clearly cannot collide with something that would be defined later.
As a concrete example, let's take:
namespace backport {
#if __cplusplus < 202002L
template <typename T>
struct type_identity { using type = T; };
#else
using ::std::type_identity<T>;
#endif
}
static_assert(std::is_same<backport::type_identity<int>::type, int>::value, "");
This safely works in all of C++11 up to C++26 (C++03 does not have <type_traits>). Could I also safely write it without the extra namespace?
#if __cplusplus < 202002L
namespace std {
template <typename T>
struct type_identity { using type = T; };
}
#endif
static_assert(std::is_same<std::type_identity<int>::type, int>::value, "");
TL;DR:
Your additions to namespace std invoke undefined behavior.
More info:
You might be right about the original rationale for introducing the rule disallowing to add stuff to namespace std.
It's nice to know the background for it, and it can be important when a change of the rule is discussed in the C++ committee.
But practically it does not really matter for determining whether you have UB or not in a given case:
Once a rule is added to the standard it is valid regardless of whether a specific case it applies to fits the original rationale.
Here the rule is very simple:
From [namespace.std]:
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified ...
Your case does not fall within the specified exceptions and therefore the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With