问题
Background
Unfortunately the current C++ standard lacks C99's exact-width types defined in the stdint
header.
The next best thing I could find (in terms of portability) was Boost
's cstdint.hpp
implementation from the Boost.Integer
library.
Concerns
That said, I've got a few problems with it:
Boost
's implementation dumps all the typedef
s in the boost namesapce
(instead of something like boost::stdint
). This is totally ugly, because now you're either forced to use a using
-directive only on the types that you're interested in (this is an extra maintenance chore), or bring the entire boost namespace
into global¹ scope (this defeats the point of namespace
s). I could, of course, be verbose and type boost::uint32_t
everywhere, for example, but this isn't very future-friendly², either.
Questions
I'm basically looking for advice. What's the best way to go about utilizing these not-yet-standard (not in C++ '03, anyway) types as transparently as possible?
For those of you who use this header, or rolled your own, how do you use these types? Blindly merge the boost namespace
into the global namespace
, prefix everything with "boost::
", wrote a header that wraps Boost.Integer
's cstdint.hpp
, etc.?
Any advice is appreciated.
Finally, having said all that (this wasn't a rant, by the way), I'm writing math-intensive code, so width-guarantees are important to me.
Clarifications
1 - Global scope is my only option when I'm writing functions / class
template
s that take these types as arguments.
2 - When the next iteration of the standard wraps stdint.h
into cstdint
, I'll be stuck with a bunch of code that's prefixed with "boost::
". This, then, will be an extra dependency (i.e., "boost/cstdint.hpp") that will be totally useless.
回答1:
You could just use stdint.h, and provide one for compilers that don't have it (e.g. for MSVC - msinttypes). Or write cstdint that is using
all of Boost's typedefs (it's a write-once, so I don't think maintenance will be problematic).
It's easy to generate, too. Using this little script, i got that. You could also add defines to check for int64
.
#ifndef GEN_CSTDINT
#define GEN_CSTDINT
#include <boost/cstdint.hpp>
using boost::int16_t;
using boost::int32_t;
using boost::int64_t;
using boost::int8_t;
using boost::int_fast16_t;
using boost::int_fast32_t;
using boost::int_fast64_t;
using boost::int_fast8_t;
using boost::int_least16_t;
using boost::int_least32_t;
using boost::int_least64_t;
using boost::int_least8_t;
using boost::intmax_t;
using boost::uint16_t;
using boost::uint32_t;
using boost::uint64_t;
using boost::uint8_t;
using boost::uint_fast16_t;
using boost::uint_fast32_t;
using boost::uint_fast64_t;
using boost::uint_fast8_t;
using boost::uint_least16_t;
using boost::uint_least32_t;
using boost::uint_least64_t;
using boost::uint_least8_t;
using boost::uintmax_t;
#endif // GEN_CSTDINT
回答2:
You could use portable version of stdint.
来源:https://stackoverflow.com/questions/1481733/portable-c-03-exact-width-types