Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Last active October 21, 2020 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derrickturk/165209d5c919321e542b3bee7c92b384 to your computer and use it in GitHub Desktop.
Save derrickturk/165209d5c919321e542b3bee7c92b384 to your computer and use it in GitHub Desktop.
Named... things, in C++
#include <cstddef>
#include <iostream>
template<std::size_t N>
struct symbol {
char name[N];
constexpr symbol(const char (&str)[N]) noexcept
{
for (std::size_t i = 0; i < N; ++i)
name[i] = str[i];
}
};
template<symbol S>
constexpr auto operator""_sym() noexcept
{
return S;
}
template<class T, symbol Name, symbol Repr = Name>
struct named {
static inline constexpr const char *name = Name.name;
static inline constexpr const char *repr = Repr.name;
T value;
friend std::ostream& operator<<(std::ostream& os, const named& o)
{
return os << o.name << " [aka " << o.repr << "]: " << o.value;
}
};
int main()
{
named<int, "x"_sym> x { 5 };
std::cout << x << '\n';
named<bool, "the.bool"_sym, "ThaBoole"_sym> b { true };
std::cout << b << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment