static_local_var.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #ifndef BOOST_CONTRACT_DETAIL_STATIC_LOCAL_VAR_HPP_
  2. #define BOOST_CONTRACT_DETAIL_STATIC_LOCAL_VAR_HPP_
  3. // Copyright (C) 2008-2018 Lorenzo Caminiti
  4. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  5. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  6. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  7. namespace boost { namespace contract { namespace detail {
  8. // This is used to hold the state of this library (already checking assertions,
  9. // failure handers, mutexes, etc.). Local static variables are used instead of
  10. // global or class-level static variables to avoid ODR errors when this library
  11. // is used as header-only.
  12. // Use T's default constructor to init the local var.
  13. template<typename Tag, typename T>
  14. struct static_local_var {
  15. static T& ref() {
  16. static T data;
  17. return data;
  18. }
  19. };
  20. // Use `init` param to init local var (Init same as or convertible to T).
  21. // NOTE: Template specializations could be used to program both this and the
  22. // template above together but some pre-C++11 compilers give errors (e.g., Clang
  23. // without -std=c++11), plus the `_init` postfix is more readable at call site.
  24. template<typename Tag, typename T, typename Init, Init init>
  25. struct static_local_var_init {
  26. static T& ref() {
  27. static T data = init;
  28. return data;
  29. }
  30. };
  31. } } } // namespace
  32. #endif // #include guard