Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/ct_string.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,21 @@ static_assert(stdx::constant_name_of_v<S> == "name"_ctst>);
using N = stdx::constant_name_of_t<S>; // stdx::cts_t<"name">
----

==== `name_for` and `constant_name_for`

When you don't know whether or not a type has a name, `name_for` will return
either its name or a `ct_string` of its type. `constant_name_for` will return
the same content as a `cts_t`.

[source,cpp]
----
static_assert(stdx::name_for<S>() == "name"_cts);
static_assert(stdx::name_for<int>() == "int"_cts);

static_assert(stdx::constant_name_for<S>() == "name"_ctst);
static_assert(stdx::constant_name_for<int>() == "int"_ctst);
----

==== `matching_name` and `same_name`

Use the `matching_name` concept to check whether a type's name matches a string.
Expand Down
14 changes: 14 additions & 0 deletions include/stdx/ct_string.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include <stdx/compiler.hpp>
#include <stdx/ct_conversions.hpp>
#include <stdx/type_traits.hpp>
#include <stdx/utility.hpp>

Expand Down Expand Up @@ -222,5 +223,18 @@ using same_name_t = std::bool_constant<same_name<T, U>>;
template <named T> struct same_name_q {
template <named U> using fn = same_name_t<T, U>;
};

template <typename T> consteval auto name_for() {
if constexpr (named<T>) {
return name_of_v<T>;
} else {
constexpr auto name = type_as_string<T>();
return ct_string<name.size() + 1>{name};
}
}

template <typename T> consteval auto constant_name_for() {
return cts_t<name_for<T>()>{};
}
} // namespace v1
} // namespace stdx
9 changes: 9 additions & 0 deletions test/ct_string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,12 @@ TEST_CASE("named object", "[ct_string]") {
STATIC_CHECK(not stdx::same_name_t<T, U>::value);
STATIC_CHECK(not stdx::same_name_q<T>::template fn<U>::value);
}

TEST_CASE("name or type fallback", "[ct_string]") {
using namespace stdx::ct_string_literals;
using T = stdx::with_name<"test">;
STATIC_CHECK(stdx::name_for<T>() == "test"_cts);
STATIC_CHECK(stdx::name_for<int>() == "int"_cts);
STATIC_CHECK(stdx::constant_name_for<T>() == "test"_ctst);
STATIC_CHECK(stdx::constant_name_for<int>() == "int"_ctst);
}