autosprintf.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* Class autosprintf - formatted output to an ostream.
  2. Copyright (C) 2002, 2012-2016 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation; either version 2.1 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. #ifndef _AUTOSPRINTF_H
  14. #define _AUTOSPRINTF_H
  15. /* This feature is available in gcc versions 2.5 and later. */
  16. #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
  17. # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() /* empty */
  18. #else
  19. /* The __-protected variants of 'format' and 'printf' attributes
  20. are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
  21. # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
  22. # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() \
  23. __attribute__ ((__format__ (__printf__, 2, 3)))
  24. # else
  25. # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() \
  26. __attribute__ ((format (printf, 2, 3)))
  27. # endif
  28. #endif
  29. #include <string>
  30. #include <iostream>
  31. namespace gnu
  32. {
  33. /* A temporary object, usually allocated on the stack, representing
  34. the result of an asprintf() call. */
  35. class autosprintf
  36. {
  37. public:
  38. /* Constructor: takes a format string and the printf arguments. */
  39. autosprintf (const char *format, ...)
  40. _AUTOSPRINTF_ATTRIBUTE_FORMAT();
  41. /* Copy constructor. */
  42. autosprintf (const autosprintf& src);
  43. /* Assignment operator. */
  44. autosprintf& operator = (autosprintf temporary);
  45. /* Destructor: frees the temporarily allocated string. */
  46. ~autosprintf ();
  47. /* Conversion to string. */
  48. operator char * () const;
  49. operator std::string () const;
  50. /* Output to an ostream. */
  51. friend inline std::ostream& operator<< (std::ostream& stream, const autosprintf& tmp)
  52. {
  53. stream << (tmp.str ? tmp.str : "(error in autosprintf)");
  54. return stream;
  55. }
  56. private:
  57. char *str;
  58. };
  59. }
  60. #endif /* _AUTOSPRINTF_H */