Achieving forward compatibility with C++11

Posted by mcmcc on Programmers See other posts from Programmers or by mcmcc
Published on 2012-04-03T19:25:53Z Indexed on 2012/04/03 23:40 UTC
Read the original article Hit count: 561

Filed under:
|

I work on a large software application that must run on several platforms. Some of these platforms support some features of C++11 (e.g. MSVS 2010) and some don't support any (e.g. GCC 4.3.x). I see this situation continuing on for several years (my best guess: 3-5 years).

Given that, I would like set up a compatibility interface such that (to whatever degree possible) people can write C++11 code that will still compile with older compilers with a minimum of maintenance. Overall, the goal is to minimize #ifdef's as much as reasonably possible while still enabling basic C++11 syntax/features on the platforms that support them, and provide emulation on the platforms that don't.

Let's start with std::move(). The most obvious way to achieve compatibility would be to put something like this in a common header file:

#if !defined(HAS_STD_MOVE)
namespace std { // C++11 emulation
  template <typename T> inline T& move(T& v) { return v; }
  template <typename T> inline const T& move(const T& v) { return v; }
}
#endif // !defined(HAS_STD_MOVE)

This allow people to write things like

std::vector<Thing> x = std::move(y);

... with impugnity. It does what they want in C++11 and it does the best it can in C++03. When we finally drop the last of the C++03 compilers, this code can remain as is.

However, according to the standard, it is illegal to inject new symbols into the std namespace. That's the theory. My question is, practically speaking, is there any harm in doing this as a way of achieving forward compatibility?

© Programmers or respective owner

Related posts about c++

Related posts about c++11