2017-05-29 17:21:11 +10:00
|
|
|
/*
|
2018-08-04 15:14:06 +10:00
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
2017-05-29 17:21:11 +10:00
|
|
|
*
|
2019-05-30 10:43:05 +10:00
|
|
|
* Copyright 2017-2019 Danny Robson <danny@nerdcruft.net>
|
2017-05-29 17:21:11 +10:00
|
|
|
*/
|
|
|
|
|
2019-05-30 10:43:05 +10:00
|
|
|
#pragma once
|
2017-05-29 17:21:11 +10:00
|
|
|
|
2019-09-04 08:06:29 +10:00
|
|
|
#include <atomic>
|
|
|
|
|
2017-05-29 17:21:11 +10:00
|
|
|
|
2018-08-05 14:42:02 +10:00
|
|
|
namespace cruft {
|
2019-09-04 08:06:29 +10:00
|
|
|
namespace detail {
|
|
|
|
template <typename TagT>
|
|
|
|
int typeidx_next (void)
|
|
|
|
{
|
|
|
|
static std::atomic<int> counter;
|
|
|
|
return ++counter;
|
|
|
|
}
|
|
|
|
}
|
2017-05-29 17:21:11 +10:00
|
|
|
|
2019-09-04 08:06:29 +10:00
|
|
|
/// Return a globally unique runtime ID for a given type (namespaced by a
|
|
|
|
/// tag type).
|
2017-05-29 17:21:11 +10:00
|
|
|
///
|
2019-05-30 10:43:05 +10:00
|
|
|
/// This is intended to be used as a lightweight type check for variants
|
2017-05-29 17:21:11 +10:00
|
|
|
/// and such without requiring RTTI.
|
|
|
|
///
|
2019-05-30 10:43:05 +10:00
|
|
|
/// The identifier is constructed at runtime and is not guaranteed to be
|
2017-05-29 17:21:11 +10:00
|
|
|
/// stable across executions (particularly in the case of threads and
|
2019-05-30 10:43:05 +10:00
|
|
|
/// other non-determinism). However it _is_ threadsafe to call this.
|
2017-05-29 17:21:11 +10:00
|
|
|
///
|
2019-05-30 10:43:05 +10:00
|
|
|
/// The value 0 will never be returned from this function and can be used
|
|
|
|
/// to indicate an 'unknown' state.
|
|
|
|
///
|
|
|
|
/// The range of identifiers is _probably_ contiguous. This should not
|
|
|
|
/// be relied upon for correctness, but may be used for performance
|
|
|
|
/// concerns.
|
2019-09-04 08:06:29 +10:00
|
|
|
///
|
|
|
|
/// \tparam T The type to register-and-retrieve the ID for
|
|
|
|
/// \tparam TagT A namespacing type; different tags will have different
|
|
|
|
/// sets of IDs. The default Tag is void.
|
|
|
|
/// \return The unique ID of the type
|
|
|
|
template <typename T, typename TagT = void>
|
2018-04-05 12:14:11 +10:00
|
|
|
int
|
2017-05-29 17:21:11 +10:00
|
|
|
typeidx (void)
|
|
|
|
{
|
2019-09-04 08:06:29 +10:00
|
|
|
static auto id = detail::typeidx_next<TagT> ();
|
2017-05-29 17:21:11 +10:00
|
|
|
return id;
|
|
|
|
}
|
|
|
|
}
|