]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/type_index/examples/constexpr14_namespace_check.cpp
1 // Copyright 2013-2017 Antony Polukhin
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See the accompanying file LICENSE_1_0.txt
5 // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
7 #include <boost/config.hpp>
10 void do_something(const T
&) {}
13 #if !defined(BOOST_NO_CXX14_CONSTEXPR) && !defined(BOOST_NO_CXX11_CONSTEXPR)
14 // Implementation of this function is not essential for the example
15 template <std::size_t N
>
16 constexpr bool starts_with(const char* name
, const char (&ns
)[N
]) noexcept
{
17 for (std::size_t i
= 0; i
< N
- 1; ++i
)
24 //[type_index_constexpr14_namespace_example
26 The following example shows that `boost::typeindex::ctti_type_index` is usable at compile time on
27 a C++14 compatible compilers.
29 In this example we'll create and use a constexpr function that checks namespace of the provided type.
32 #include <boost/type_index/ctti_type_index.hpp>
34 // Helper function that returns true if `name` starts with `substr`
35 template <std::size_t N
>
36 constexpr bool starts_with(const char* name
, const char (&substr
)[N
]) noexcept
;
39 // Function that returns true if `T` declared in namespace `ns`
40 template <class T
, std::size_t N
>
41 constexpr bool in_namespace(const char (&ns
)[N
]) noexcept
{
42 const char* name
= boost::typeindex::ctti_type_index::type_id
<T
>().raw_name();
44 // Some compilers add `class ` or `struct ` before the namespace, so we need to skip those words first
45 if (starts_with(name
, "class ")) {
46 name
+= sizeof("class ") - 1;
47 } else if (starts_with(name
, "struct ")) {
48 name
+= sizeof("struct ") - 1;
51 return starts_with(name
, ns
) && starts_with(name
+ N
- 1, "::");
55 Now when we have that wonderfull function, we can do static assertions and other compile-time validations:
58 namespace my_project
{
61 void serialize(const T
& value
) {
63 in_namespace
<T
>("my_project::types") || in_namespace
<T
>("my_project::types_ext"),
64 "Only types from namespaces `my_project::types` and `my_project::types_ext` are allowed to be serialized using `my_project::serializer`"
67 // Actual implementation of the serialization goes below
77 } // namespace my_project
80 my_project::serializer s
;
81 my_project::types::foo f
;
82 my_project::types::bar b
;
88 // s.serialize(sh); // Fails the static_assert!
90 //] [/type_index_constexpr14_namespace_example]
92 #else // #if !defined(BOOST_NO_CXX14_CONSTEXPR) && !defined(BOOST_NO_CXX11_CONSTEXPR)