Extending std namespace with backported code
Asked Answered
T

0

6

Some background:

Extending namespace std is undefined-behaviour(UB) unless it is a template specialization [1]:

It is undefined behavior to add declarations or definitions to namespace std or to any namespace nested within std, with a few exceptions noted below

There also questions on SO which also say it's an UB and a bad idea [2, 3].

We use boost::tr1 on platforms that don't have tr1 support (e.g., WinCE, WM). Boost does exactly this: injects its own implementation into std::tr1 if tr1 is not provided.

For example in boost/tr1/memory.hpp:

namespace std{ namespace tr1{ 
   using ::boost::bad_weak_ptr;
   using ::boost::shared_ptr;
   ...
} }

My questions are:

  • Does this mean that it is UB if boost::tr1 is used with non-tr1 compilers?

  • Alternatively, is it okay to inject backports into std as long as developer makes sure that backported functionality is unavailable?

  • If it is okay, can one take it one step further and inject boost::tr1 into std instead of std::tr1?

Tennessee answered 8/2, 2018 at 11:28 Comment(4)
Most of the UB comes from the fact that an implementation is allowed to already add specializations and additional overloads to namespace std. If you do that too, there will be conflicts. Boost just might have their tricks sanctioned by the compiler manufacturers, in which case it is implementation defined instead of UB.Overweary
Just... don't do it. Put stuff in namespace mystd or something instead. Then you won't have to deal with any of these questions.Epps
@Epps it seems so. I am now leaning towards std_ solutionTennessee
If the idea is to backport then I'd say you count as an implementor by definition and thus you are implicitly allowed to do the stuff in namespace std; the question is moot otherwise as the alternative is simply nonfunctional backports: how would you make code in function signatures or template parameters that uses eg.: typename = std::enable_if<....> use a enable_if located somewhere else instead? There's no using in signatures. That's just one case. As for whether it's UB, "do as the compiler does" and you'll at most be as much UB as them.Alexei

© 2022 - 2024 — McMap. All rights reserved.