I am not sure the title of the question is proper. Here is the problem. I am writing a library which use some c++11 library features. Clearly not all implementations support these libraries yet and thus there is the portability problem. It does not matter which library is of concern here. One solution is to use boost, which already provide a lot c++11 libraries. So my solution is to define a macro, say USE_CXX11
, and define a new namespace say internal
and introduce names into this internal namespace dependent on the macros. For example say I need to use a name foo
from a c++ library <foo>
, which is also available in <boost/foo/foo.hpp>
. What I do is
#ifdef USE_CXX11
#include <foo>
#else
#include <boost/foo/foo.hpp>
#endif
namespace internal {
#ifdef USE_CXX11
using std::foo;
#else
using boost::foo::foo;
#endif
}
And in the rest of the library I only use internal::foo
. Third party code which use this library can define the proper macro to indicate if they have a working c++ 11 implementation or they can only use boost. And my library will pickup the right header and namespace. This works so far. Hope I have explained my intention well.
But the above solutions seems very ugly to me. Is there any better practice for this kind of thing? Or is there any possible situations that this approach will not work?
Your solution looks fine to me; the only problem will be (as Chet mentions) in the cases where the Boost and C++11 interfaces and/or implementations differ.
In fact, I do that in the Boost.Algorithms library (new in the upcoming 1.50 release)
namespace boost { namespace algorithm {
#if __cplusplus >= 201103L
using std::find_if_not; // Section 25.2.5
#else
template<typename InputIterator, typename Predicate>
InputIterator find_if_not ( InputIterator first, InputIterator last, Predicate p )
{
for ( ; first != last; ++first )
if ( !p(*first))
break;
return first;
}
#endif
}}
I don't see this as a workable solution. Conditionally switching between classes will restrict their use to only those member functions having the same signatures and semantics. You are also redirecting access to The Standard Library which may feel unnatural for many developers.
If usability is a concern between C++03 and C++11 then you should definitely go with Boost for everything. If C++11 is your only target you may have better success evaluating the various compilers to see what language and library features they support. Pick those that are well supported and considered bug free. For everything else use Boost and refactor later if necessary to support more C++11 library features. You will be much better off using the libraries in tandem rather than switching between them.
You can get a start with the status page of GCC's C++ Standard Library implementation .
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