Skip to content

Instantly share code, notes, and snippets.

@derrickturk

derrickturk/symbol.cpp

Last active Oct 21, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.