Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C++ (Circle)
CIRCT
Clean
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
Go
Haskell
HLSL
Hook
Hylo
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Nim
Objective-C
Objective-C++
OCaml
OpenCL C
Pascal
Pony
Python
Racket
Ruby
Rust
Snowball
Scala
Solidity
Spice
Swift
LLVM TableGen
Toit
TypeScript Native
V
Vala
Visual Basic
Zig
Javascript
GIMPLE
cppx source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
CppCon 2017
CppCon 2018
p1240r1
p1240r2 trunk
p2320 trunk
Options
Source code
#include <experimental/meta> #include <experimental/compiler> #include <iostream> #include <tuple> #include <string_view> using namespace std::experimental; template<size_t x> struct size_ { constexpr auto operator()() { return x; } constexpr operator size_t() { return x; } size_t value = x; }; template<size_t value> constexpr auto size_c = size_<value>{}; template<typename T> struct mem_ptr {}; template<typename T, typename Tvalue> struct mem_ptr<Tvalue T::*> { using value_type = Tvalue; using type = T; decltype(auto) operator()(T & x) { return x.*ptr; } std::string_view name; Tvalue T::*ptr; }; mem_ptr(auto, auto x) -> mem_ptr<decltype(x)>; template<typename T> struct accessor { consteval { auto clazz = reflexpr(T); size_t idx = 0; for(auto member: meta::data_member_range{clazz}) { -> fragment struct { constexpr static auto get(size_<%{idx}>) { return mem_ptr{meta::name_of(%{member}), &typename(%{clazz})::unqualid(%{member})}; } }; ++idx; } -> fragment struct { constexpr static auto size = size_c<%{idx}>; }; }; template<size_t n> auto operator[](size_<n> idx) { return this->get(idx); } }; namespace std { template<typename T> struct tuple_size<::accessor<T>>: std::integral_constant<size_t, ::accessor<T>::size.value> {}; template<typename T, size_t idx> struct tuple_element<idx, ::accessor<T>> { using type = decltype(::accessor<T>::get(size_c<idx>)); }; } template<size_t n, typename T> decltype(auto) get(::accessor<T> & a) { return a.get(size_c<n>); } struct point { double x, y; }; int main() { point p{123, 1234}; accessor<point> acc; auto && [a, b] = acc; std::cerr << acc[size_c<0>](p) << std::endl; acc[size_c<0>](p) = 321; std::cerr << acc[size_c<0>](p) << std::endl; std::cerr << acc[size_c<1>](p) << std::endl; std::cerr << a.name << std::endl; std::cerr << b.name << std::endl; }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
About the author
Statistics
Changelog
Version tree