libcruft-util/typeidx.hpp

39 lines
1.2 KiB
C++

/*
* 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/.
*
* Copyright 2017-2019 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include <cstdint>
namespace cruft {
namespace detail { int typeidx_next (void); }
/// Return a globally unique runtime ID for a given type.
///
/// This is intended to be used as a lightweight type check for variants
/// and such without requiring RTTI.
///
/// The identifier is constructed at runtime and is not guaranteed to be
/// stable across executions (particularly in the case of threads and
/// other non-determinism). However it _is_ threadsafe to call this.
///
/// 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.
template <typename T>
int
typeidx (void)
{
static auto id = detail::typeidx_next ();
return id;
}
}