SlideShare a Scribd company logo
1 of 59
Download to read offline
Reflection in C++Next
Anton Bikineev, 2017
Agenda
Reflection in C++Next
1. Reflection
2. Surviving proposals
• P0194R3: Static reflection
• P0590R0: A design for static reflection
3. Examples
Reflection or introspection?
Reflection in C++Next
Type introspection is the ability of a program to examine the
type or properties of an object at runtime.
Reflection is the ability of a computer program to examine,
introspect, and modify its own structure and behavior at
runtime.
(from Wikipedia)
Reflection or introspection?
Reflection in C++Next
Static type introspection is the ability of a program to examine
the type or properties of an object at compile-time.
Static reflection is the ability of a computer program to
examine, introspect, and modify its own structure and
behavior at compile-time.
Introspection? Type traits!
Reflection in C++Next
namespace std {
template <class T>
struct is_integral {
constexpr static bool value = /* */true;
};
template <class T> /* since c++14 */
constexpr bool is_integral_v = is_integral<T>::value;
template <class T>
struct add_pointer {
using type = T*;
};
template <class T>
using add_pointer_t = typename add_pointer<T>::type;
}
Introspection? Type traits!
Reflection in C++Next
template <class Archive, class T>
void load(const Archive& ar, T& t) {
if constexpr (std::is_integral_v<T>)
load_integral(ar, t);
if constexpr (std::is_floating_point_v<T>)
load_fp(ar, t);
else if constexpr (std::is_trivially_copyable_v<T>)
load_memset(ar, t);
else
load_unoptimized(ar, t);
}
Introspection? Type traits!
Reflection in C++Next
template <class T, class enable = void>
struct has_foo: std::false_type {};
template <class T>
struct has_foo<T,
std::void_t<decltype(std::declval<T>().foo())>>:
std::true_type {};
Introspection? Type traits!
Reflection in C++Next
• works only with types!
• no way to traverse members!
Reflection
Reflection in C++Next
Static reflection is the ability of a computer program to
examine, introspect, and modify its own structure and
behavior at compile-time.
Reflection
Reflection in C++Next
Static reflection is the ability of a computer program to
examine, introspect, and modify its own structure and
behavior at compile-time.
Metaprogramming definition
Reflection in C++Next
Metaprogramming is the writing of computer programs
that write or manipulate other programs (or themselves)
as their data, or that do part of the work at compile time
that would otherwise be done at run-time.
(from Wikipedia, some rev.)
C++ template metaprogramming
Reflection in C++Next
auto multiply_by_two(const std::array<int, 3>& array) {
auto result = array;
for (auto& i: result)
i *= 2;
return result;
}
std::array<int, 3> arr1{1, 2, 3};
auto arr2 = multiply_by_two(arr1);
C++ template metaprogramming
Reflection in C++Next
template <class T>
struct multiply_by_two;
template <class T, T... I>
struct multiply_by_two<std::integer_sequence<T, I...>> {
using type = std::integer_sequence<T, (I * 2)...>;
};
using seq1 = std::integer_sequence<int, 1, 2, 3>;
using seq2 = multiply_by_two<seq1>::type;
C++ constexpr metaprogramming
Reflection in C++Next
constexpr
auto multiply_by_two(const std::array<int, 3>& array) {
auto result = array;
for (auto& i: result)
i *= 2;
return result;
}
constexpr std::array<int, 3> arr1{1, 2, 3};
constexpr auto arr2 = multiply_by_two(arr1);
Reflection?
Reflection in C++Next
Reflection?
Reflection in C++Next
What we actually need…
Reflection in C++Next
struct foo {
int a;
double b;
string c;
};
struct soa_foo {
vector<int> as;
vector<double> bs;
vector<string> cs;
};
Reflection in C++Next
class Person
{
[[getter, setter]] std::string name;
[[getter, setter]] std::string email;
};
What we actually need…
Reflection in C++Next
class Person
{
[[getter, setter, serialized]] std::string name;
[[getter, setter, serialized]] std::string email;
};
What we actually need…
Reflection in C++Next
class [[polymorphically_serialized]] Person: IPerson
{
Person() { /* initializing code here */ }
[[getter, setter, serialized]] std::string name;
[[getter, setter, serialized]] std::string email;
};
What we actually need…
Study Group 7: Reflection
Reflection in C++Next
• N4428: Type property queries
- 4th revision
- date: 2015-04-08
• P0255R0: Reflection via template pack expansion
- 5th revision
- date: 2016-02-12
• P0194R3: Static reflection
- 7th revision
- date: 2017-02-06
• P0590R0: A design for static reflection
- 1st revision
- date: 2017-02-05
Study Group 7: Reflection
Reflection in C++Next
• N4428: Type property queries
- 4th revision
- date: 2015-04-08
• P0255R0: Reflection via template pack expansion
- 5th revision
- date: 2016-02-12
• P0194R3: Static reflection
- 7th revision
- date: 2017-02-06
• P0590R0: A design for static reflection
- 1st revision
- date: 2017-02-05
Static reflection (P0194R3)
Reflection in C++Next
by Matúš Chochlík,
Axel Naumann,
David Sankel
P0194R3: Static reflection
Reflection in C++Next
• core-language changes:
- operator $reflect(x);
- where x is an id-expression;
- returns a unique generated type for an entity x;
- this type satisfies one or more concepts defined
in the library;
- you operate on these types (metaobjects) by
calling meta- operations.
• library changes:
- std::reflect::Concept<m>
- std::reflect::Operation<m>
P0194R3: Static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
using person_m = $reflect(person);
static_assert(std::reflect::Variable<person_m>());
std::cout << std::reflect::get_base_name_v<person_m>;
P0194R3: Static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
using person_m = $reflect(person);
static_assert(std::reflect::Variable<person_m>());
std::cout << std::reflect::get_base_name_v<person_m>;
using type_m = std::reflect::get_type_t<person_m>;
static_assert(std::reflect::Type<type_m>());
P0194R3: Static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
using person_m = $reflect(person);
static_assert(std::reflect::Variable<person_m>());
std::cout << std::reflect::get_base_name_v<person_m>;
using type_m = std::reflect::get_type_t<person_m>;
static_assert(std::reflect::Type<type_m>());
using real_type =
std::reflect::get_reflected_type_t<type_m>;
static_assert(std::is_same_v<real_type, std::string>);
P0194R3: Static reflection.
Meta-object concepts
Reflection in C++Next
namespace std::experimental::reflect {
template <class T> concept bool Object();
template <class T> concept bool ObjectSequence();
template <Object T> concept bool Named();
template <Object T> concept bool Alias();
template <Object T> concept bool RecordMember();
template <Object T> concept bool Enumerator();
template <Object T> concept bool Variable();
template <Object T> concept bool ScopeMember();
template <Object T> concept bool Typed();
template <Object T> concept bool Namespace();
template <Object T> concept bool GlobalScope();
template <Object T> concept bool Class();
template <Object T> concept bool Enum();
template <Object T> concept bool Record();
template <Object T> concept bool Scope();
template <Object T> concept bool Type();
template <Object T> concept bool Constant();
template <Object T> concept bool Base();
}
P0194R3: Static reflection.
Class-like things
Reflection in C++Next
template <Object T> concept bool Record();
- a union or a class
template <Object T> concept bool Class();
- a class or a struct
template <Object T> concept bool Base();
- base classes
template <Object T> concept bool RecordMember();
- data member and member types
P0194R3: Static reflection.
Scopes
Reflection in C++Next
template <Object T> concept bool Namespace();
- a namespace
template <Object T> concept bool Scope();
- a namespace, class or enumeration scope
template <Object T> concept bool ScopeMember();
- something in a scope
template <Object T> concept bool GlobalScope();
- the global namespace, $reflect(::)
P0194R3: Static reflection.
Enums
Reflection in C++Next
template <Object T> concept bool Enum();
- an enum
template <Object T> concept bool Enumerator();
- an enumerator
P0194R3: Static reflection.
Types
Reflection in C++Next
template <Object T> concept bool Typed();
- something that has a type, e.g. member-variable
template <Object T> concept bool Type();
- a type
P0194R3: Static reflection.
Expressions
Reflection in C++Next
template <Object T> concept bool Variable();
- a variable
template <Object T> concept bool Constant();
- a constant-expression, like an enumerator
P0194R3: Static reflection.
Other
Reflection in C++Next
template <Object T> concept bool Named();
- something with a name;
template <Object T> concept bool Alias();
- an alias, like a typedef
template <Object T> concept bool ObjectSequence();
- object-sequence, type-list…
P0194R3:
Meta-object operations by
examples
Reflection in C++Next
P0194R3: Static reflection.
Enum-to-string
Reflection in C++Next
template <class Enum>
std::string to_string(Enum e) {
using namespace std::reflect;
using e_m = $reflect(Enum);
static_assert(std::reflect::Enum<e_m>());
std::string result;
for_each<get_enumerators_t<e_m>>([&](auto m) {
using en_m = decltype(m);
if (get_constant_v<en_m> == e)
result = get_base_name_v<en_m>;
});
return result;
}
P0194R3: Static reflection.
Generic equal
Reflection in C++Next
template <class T>
bool generic_equal(const T& a, const T& b) {
using namespace std::reflect;
using T_m = $reflect(T);
static_assert(std::reflect::Class<e_m>());
bool result = true;
for_each<get_data_members_t<T_m>>([&](auto m) {
using m_t = decltype(m);
result &= a.*get_pointer_v<m_t> ==
b.*get_pointer_v<m_t>;
});
return result;
}
P0194R3: Static reflection.
Generic equal with unreflect
Reflection in C++Next
template <class T>
bool generic_equal(const T& a, const T& b) {
using namespace std::reflect;
using T_m = $reflect(T);
static_assert(std::reflect::Class<e_m>());
bool result = true;
for_each<get_data_members_t<T_m>>([&](auto m) {
result &= a.$unreflect(m) ==
b.$unreflect(m);
});
return result;
}
P0194R3: Static reflection.
Templates parametrized by namespace
Reflection in C++Next
namespace foo {
void func1(const std::string&);
void func2(int);
int func3(int);
}
namespace bar {
void func1(const std::string&);
void func2(int);
int func3(int);
}
P0194R3: Static reflection.
Templates parametrized by namespace
Reflection in C++Next
template <class MN>
void algorithm(const string& str, int i) {
// [foo|bar]::func1(str)
$unreflect(MN)::func1(str);
// [foo|bar]::func2([foo|bar]::func3(i))
$unreflect(MN)::func2($unreflect(MN)::func3(i));
}
void func(const string& str, int i, bool want_foo) {
if (want_foo)
algorithm<$reflect(foo)>(str, i);
else
algorithm<$reflect(bar)>(str, i);
}
P0194R3: Static reflection.
String to identifier transformation
Reflection in C++Next
struct foo {
int bar;
};
constexpr const char* bar_name =
get_base_name_v<$reflect(foo::bar)>;
int get_???bar_name???(const foo&);
P0194R3: Static reflection.
String to identifier transformation
Reflection in C++Next
struct foo {
int bar;
};
constexpr const char* bar_name =
get_base_name_v<$reflect(foo::bar)>;
int $identifier(ct_concat(“get_”, bar_name))(const foo&);
P0194R3: Static reflection.
String to identifier transformation
Reflection in C++Next
struct foo {
int a;
double b;
string c;
};
struct soa_foo {
vector<int> as;
vector<double> bs;
vector<string> cs;
};
P0194R3: Static reflection
Reflection in C++Next
• supported:
- variables;
- data members;
- member types;
- enumerators;
- template instantiations;
- aliases
P0194R3: Static reflection
Reflection in C++Next
• not supported:
- declarations in namespaces (except for types);
- functions (yet);
- class templates (yet)
P0194R3: Static reflection.
Pros and cons
Reflection in C++Next
• Pros:
- reflection of different entities is supported;
- very lazy instantiation, only queried data is
instantiated;
- “you don’t pay for what you don’t use” at
compile-time;
- a good base for building higher-level and
domain-specific libraries;
- very extensible
P0194R3: Static reflection.
Pros and cons
Reflection in C++Next
• Cons:
- awkward and verbose usage;
- no attribute ideas
A design for static reflection
(P0590R0)
Reflection in C++Next
by Andrew Sutton,
Herb Sutter
P0590R0: A design for static reflection
Reflection in C++Next
• core-language changes:
- operator $x;
- where x is an id-expression;
- returns a unique object of a generated type for
an entity x;
- the object represents its meta information;
- you operate on these objects by calling
member-functions
• library changes:
- std::meta::reflection_type<X>
P0590R0: A design for static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
auto person_m = $person;
static_assert(std::meta::is_variable_v<
decltype(person_m)>);
std::cout << person_m.name();
P0590R0: A design for static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
auto person_m = $person;
static_assert(std::meta::is_variable_v<
decltype(person_m)>);
std::cout << person_m.name();
auto type_m = person_m.type();
static_assert(std::meta::is_type_v<decltype(type_m)>);
P0590R0: A design for static reflection.
Simple example
Reflection in C++Next
std::string person = "John";
auto person_m = $person;
static_assert(std::meta::is_variable_v<
decltype(person_m)>);
std::cout << person_m.name();
auto type_m = person_m.type();
static_assert(std::meta::is_type_v<decltype(type_m)>);
using real_type = ???;
P0194R3 vs P0590R0
Enum-to-string
Reflection in C++Next
template <class Enum>
std::string to_string(Enum e) {
using namespace std::reflect;
using e_m = $reflect(Enum);
static_assert(std::reflect::Enum<e_m>());
std::string result;
for_each<get_enumerators_t<e_m>>([&](auto m) {
using en_m = decltype(m);
if (get_constant_v<en_m> == e)
result = get_base_name_v<en_m>;
});
return result;
}
P0194R3 vs P0590R0
Enum-to-string
Reflection in C++Next
template <class Enum>
std::string to_string(Enum e) {
using namespace std::meta;
auto e_m = $Enum;
static_assert(std::meta::is_enum_v<decltype(e_m)>);
std::string result;
for_each(e_m.enumerators(), [&](auto m) {
if (m.value() == e)
result = m.name();
});
return result;
}
P0194R3 vs P0590R0
Enum-to-string
Reflection in C++Next
template <class Enum>
std::string to_string(Enum e) {
using namespace std::meta;
auto e_m = $Enum;
static_assert(std::meta::is_enum_v<decltype(e_m)>);
std::string result;
for (auto e: e_m.enumerators())
if (m.value() == e)
result = m.name();
return result;
}
P0194R3 vs P0590R0
Generic equal
Reflection in C++Next
template <class T>
bool generic_equal(const T& a, const T& b) {
bool result = true;
for (auto member: $T.member_variables()) {
auto ptr = member.pointer();
result &= a.*ptr == b.*ptr;
}
return result;
}
P0590R0: A design for static reflection.
Pros and cons
Reflection in C++Next
• Pros:
- reflection of different entities is supported;
- better syntax;
- a good base for building higher-level and
domain-specific libraries;
- extensible
P0590R0: A design for static reflection.
Pros and cons
Reflection in C++Next
• Cons:
- some extra data may still be instantiated by
compiler;
- no attribute ideas
Thank you for your attention!
Reflection in C++Next

More Related Content

What's hot

What's hot (20)

TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
C++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingC++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogramming
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
 
Tensor comprehensions
Tensor comprehensionsTensor comprehensions
Tensor comprehensions
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
C++ references
C++ referencesC++ references
C++ references
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
 
Tiramisu概要
Tiramisu概要Tiramisu概要
Tiramisu概要
 
TensorFlow local Python XLA client
TensorFlow local Python XLA clientTensorFlow local Python XLA client
TensorFlow local Python XLA client
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Qt Rest Server
Qt Rest ServerQt Rest Server
Qt Rest Server
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 

Viewers also liked

Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Platonov Sergey
 

Viewers also liked (9)

Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
Повседневный С++: алгоритмы и итераторы @ C++ Russia 2017
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines
 
Parallel STL
Parallel STLParallel STL
Parallel STL
 
Григорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптерГригорий Демченко, Универсальный адаптер
Григорий Демченко, Универсальный адаптер
 
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и JavascriptСергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и Javascript
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
 
Догнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_castДогнать и перегнать boost::lexical_cast
Догнать и перегнать boost::lexical_cast
 
Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализация
 

Similar to Антон Бикинеев, Reflection in C++Next

Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
Paulo Morgado
 

Similar to Антон Бикинеев, Reflection in C++Next (20)

Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
 
HexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profitHexRaysCodeXplorer: object oriented RE for fun and profit
HexRaysCodeXplorer: object oriented RE for fun and profit
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Bw14
Bw14Bw14
Bw14
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 

More from Sergey Platonov

More from Sergey Platonov (20)

Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
 
Василий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексиейВасилий Сорокин, Простой REST сервер на Qt с рефлексией
Василий Сорокин, Простой REST сервер на Qt с рефлексией
 
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного багаЛев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
Лев Казаркин, Удивительные приключения регистров SSE или в поисках одного бага
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.io
 
Григорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизацияГригорий Демченко, Асинхронность и неблокирующая синхронизация
Григорий Демченко, Асинхронность и неблокирующая синхронизация
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17
 
Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++Павел Беликов, Как избежать ошибок, используя современный C++
Павел Беликов, Как избежать ошибок, используя современный C++
 
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на QtДенис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
Денис Кандров, Пушкова Евгения, QSpec: тестирование графических приложений на Qt
 
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
Александр Тарасенко, Использование python для автоматизации отладки С/C++ код...
 
Павел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладкаПавел Довгалюк, Обратная отладка
Павел Довгалюк, Обратная отладка
 
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворковНикита Глушков, К вопросу о реализации кроссплатформенных фреймворков
Никита Глушков, К вопросу о реализации кроссплатформенных фреймворков
 
Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...Dori Exterman, Considerations for choosing the parallel computing strategy th...
Dori Exterman, Considerations for choosing the parallel computing strategy th...
 
Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++Александр Фокин, Рефлексия в C++
Александр Фокин, Рефлексия в C++
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++
 
Михаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STLМихаил Матросов, Повседневный С++: boost и STL
Михаил Матросов, Повседневный С++: boost и STL
 
Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++Борис Сазонов, RAII потоки и CancellationToken в C++
Борис Сазонов, RAII потоки и CancellationToken в C++
 
Илья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кодаИлья Шишков, Принципы создания тестируемого кода
Илья Шишков, Принципы создания тестируемого кода
 
Антон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствамиАнтон Наумович, Система автоматической крэш-аналитики своими средствами
Антон Наумович, Система автоматической крэш-аналитики своими средствами
 
Андрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кодаАндрей Карпов, Приватные байки от разработчиков анализатора кода
Андрей Карпов, Приватные байки от разработчиков анализатора кода
 
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++ Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
Юрий Ефимочев, Компилируемые в реальном времени DSL для С++
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 

Антон Бикинеев, Reflection in C++Next

  • 2. Agenda Reflection in C++Next 1. Reflection 2. Surviving proposals • P0194R3: Static reflection • P0590R0: A design for static reflection 3. Examples
  • 3. Reflection or introspection? Reflection in C++Next Type introspection is the ability of a program to examine the type or properties of an object at runtime. Reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime. (from Wikipedia)
  • 4. Reflection or introspection? Reflection in C++Next Static type introspection is the ability of a program to examine the type or properties of an object at compile-time. Static reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at compile-time.
  • 5. Introspection? Type traits! Reflection in C++Next namespace std { template <class T> struct is_integral { constexpr static bool value = /* */true; }; template <class T> /* since c++14 */ constexpr bool is_integral_v = is_integral<T>::value; template <class T> struct add_pointer { using type = T*; }; template <class T> using add_pointer_t = typename add_pointer<T>::type; }
  • 6. Introspection? Type traits! Reflection in C++Next template <class Archive, class T> void load(const Archive& ar, T& t) { if constexpr (std::is_integral_v<T>) load_integral(ar, t); if constexpr (std::is_floating_point_v<T>) load_fp(ar, t); else if constexpr (std::is_trivially_copyable_v<T>) load_memset(ar, t); else load_unoptimized(ar, t); }
  • 7. Introspection? Type traits! Reflection in C++Next template <class T, class enable = void> struct has_foo: std::false_type {}; template <class T> struct has_foo<T, std::void_t<decltype(std::declval<T>().foo())>>: std::true_type {};
  • 8. Introspection? Type traits! Reflection in C++Next • works only with types! • no way to traverse members!
  • 9. Reflection Reflection in C++Next Static reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at compile-time.
  • 10. Reflection Reflection in C++Next Static reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at compile-time.
  • 11. Metaprogramming definition Reflection in C++Next Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at run-time. (from Wikipedia, some rev.)
  • 12. C++ template metaprogramming Reflection in C++Next auto multiply_by_two(const std::array<int, 3>& array) { auto result = array; for (auto& i: result) i *= 2; return result; } std::array<int, 3> arr1{1, 2, 3}; auto arr2 = multiply_by_two(arr1);
  • 13. C++ template metaprogramming Reflection in C++Next template <class T> struct multiply_by_two; template <class T, T... I> struct multiply_by_two<std::integer_sequence<T, I...>> { using type = std::integer_sequence<T, (I * 2)...>; }; using seq1 = std::integer_sequence<int, 1, 2, 3>; using seq2 = multiply_by_two<seq1>::type;
  • 14. C++ constexpr metaprogramming Reflection in C++Next constexpr auto multiply_by_two(const std::array<int, 3>& array) { auto result = array; for (auto& i: result) i *= 2; return result; } constexpr std::array<int, 3> arr1{1, 2, 3}; constexpr auto arr2 = multiply_by_two(arr1);
  • 17. What we actually need… Reflection in C++Next struct foo { int a; double b; string c; }; struct soa_foo { vector<int> as; vector<double> bs; vector<string> cs; };
  • 18. Reflection in C++Next class Person { [[getter, setter]] std::string name; [[getter, setter]] std::string email; }; What we actually need…
  • 19. Reflection in C++Next class Person { [[getter, setter, serialized]] std::string name; [[getter, setter, serialized]] std::string email; }; What we actually need…
  • 20. Reflection in C++Next class [[polymorphically_serialized]] Person: IPerson { Person() { /* initializing code here */ } [[getter, setter, serialized]] std::string name; [[getter, setter, serialized]] std::string email; }; What we actually need…
  • 21. Study Group 7: Reflection Reflection in C++Next • N4428: Type property queries - 4th revision - date: 2015-04-08 • P0255R0: Reflection via template pack expansion - 5th revision - date: 2016-02-12 • P0194R3: Static reflection - 7th revision - date: 2017-02-06 • P0590R0: A design for static reflection - 1st revision - date: 2017-02-05
  • 22. Study Group 7: Reflection Reflection in C++Next • N4428: Type property queries - 4th revision - date: 2015-04-08 • P0255R0: Reflection via template pack expansion - 5th revision - date: 2016-02-12 • P0194R3: Static reflection - 7th revision - date: 2017-02-06 • P0590R0: A design for static reflection - 1st revision - date: 2017-02-05
  • 23. Static reflection (P0194R3) Reflection in C++Next by Matúš Chochlík, Axel Naumann, David Sankel
  • 24. P0194R3: Static reflection Reflection in C++Next • core-language changes: - operator $reflect(x); - where x is an id-expression; - returns a unique generated type for an entity x; - this type satisfies one or more concepts defined in the library; - you operate on these types (metaobjects) by calling meta- operations. • library changes: - std::reflect::Concept<m> - std::reflect::Operation<m>
  • 25. P0194R3: Static reflection. Simple example Reflection in C++Next std::string person = "John"; using person_m = $reflect(person); static_assert(std::reflect::Variable<person_m>()); std::cout << std::reflect::get_base_name_v<person_m>;
  • 26. P0194R3: Static reflection. Simple example Reflection in C++Next std::string person = "John"; using person_m = $reflect(person); static_assert(std::reflect::Variable<person_m>()); std::cout << std::reflect::get_base_name_v<person_m>; using type_m = std::reflect::get_type_t<person_m>; static_assert(std::reflect::Type<type_m>());
  • 27. P0194R3: Static reflection. Simple example Reflection in C++Next std::string person = "John"; using person_m = $reflect(person); static_assert(std::reflect::Variable<person_m>()); std::cout << std::reflect::get_base_name_v<person_m>; using type_m = std::reflect::get_type_t<person_m>; static_assert(std::reflect::Type<type_m>()); using real_type = std::reflect::get_reflected_type_t<type_m>; static_assert(std::is_same_v<real_type, std::string>);
  • 28. P0194R3: Static reflection. Meta-object concepts Reflection in C++Next namespace std::experimental::reflect { template <class T> concept bool Object(); template <class T> concept bool ObjectSequence(); template <Object T> concept bool Named(); template <Object T> concept bool Alias(); template <Object T> concept bool RecordMember(); template <Object T> concept bool Enumerator(); template <Object T> concept bool Variable(); template <Object T> concept bool ScopeMember(); template <Object T> concept bool Typed(); template <Object T> concept bool Namespace(); template <Object T> concept bool GlobalScope(); template <Object T> concept bool Class(); template <Object T> concept bool Enum(); template <Object T> concept bool Record(); template <Object T> concept bool Scope(); template <Object T> concept bool Type(); template <Object T> concept bool Constant(); template <Object T> concept bool Base(); }
  • 29. P0194R3: Static reflection. Class-like things Reflection in C++Next template <Object T> concept bool Record(); - a union or a class template <Object T> concept bool Class(); - a class or a struct template <Object T> concept bool Base(); - base classes template <Object T> concept bool RecordMember(); - data member and member types
  • 30. P0194R3: Static reflection. Scopes Reflection in C++Next template <Object T> concept bool Namespace(); - a namespace template <Object T> concept bool Scope(); - a namespace, class or enumeration scope template <Object T> concept bool ScopeMember(); - something in a scope template <Object T> concept bool GlobalScope(); - the global namespace, $reflect(::)
  • 31. P0194R3: Static reflection. Enums Reflection in C++Next template <Object T> concept bool Enum(); - an enum template <Object T> concept bool Enumerator(); - an enumerator
  • 32. P0194R3: Static reflection. Types Reflection in C++Next template <Object T> concept bool Typed(); - something that has a type, e.g. member-variable template <Object T> concept bool Type(); - a type
  • 33. P0194R3: Static reflection. Expressions Reflection in C++Next template <Object T> concept bool Variable(); - a variable template <Object T> concept bool Constant(); - a constant-expression, like an enumerator
  • 34. P0194R3: Static reflection. Other Reflection in C++Next template <Object T> concept bool Named(); - something with a name; template <Object T> concept bool Alias(); - an alias, like a typedef template <Object T> concept bool ObjectSequence(); - object-sequence, type-list…
  • 36. P0194R3: Static reflection. Enum-to-string Reflection in C++Next template <class Enum> std::string to_string(Enum e) { using namespace std::reflect; using e_m = $reflect(Enum); static_assert(std::reflect::Enum<e_m>()); std::string result; for_each<get_enumerators_t<e_m>>([&](auto m) { using en_m = decltype(m); if (get_constant_v<en_m> == e) result = get_base_name_v<en_m>; }); return result; }
  • 37. P0194R3: Static reflection. Generic equal Reflection in C++Next template <class T> bool generic_equal(const T& a, const T& b) { using namespace std::reflect; using T_m = $reflect(T); static_assert(std::reflect::Class<e_m>()); bool result = true; for_each<get_data_members_t<T_m>>([&](auto m) { using m_t = decltype(m); result &= a.*get_pointer_v<m_t> == b.*get_pointer_v<m_t>; }); return result; }
  • 38. P0194R3: Static reflection. Generic equal with unreflect Reflection in C++Next template <class T> bool generic_equal(const T& a, const T& b) { using namespace std::reflect; using T_m = $reflect(T); static_assert(std::reflect::Class<e_m>()); bool result = true; for_each<get_data_members_t<T_m>>([&](auto m) { result &= a.$unreflect(m) == b.$unreflect(m); }); return result; }
  • 39. P0194R3: Static reflection. Templates parametrized by namespace Reflection in C++Next namespace foo { void func1(const std::string&); void func2(int); int func3(int); } namespace bar { void func1(const std::string&); void func2(int); int func3(int); }
  • 40. P0194R3: Static reflection. Templates parametrized by namespace Reflection in C++Next template <class MN> void algorithm(const string& str, int i) { // [foo|bar]::func1(str) $unreflect(MN)::func1(str); // [foo|bar]::func2([foo|bar]::func3(i)) $unreflect(MN)::func2($unreflect(MN)::func3(i)); } void func(const string& str, int i, bool want_foo) { if (want_foo) algorithm<$reflect(foo)>(str, i); else algorithm<$reflect(bar)>(str, i); }
  • 41. P0194R3: Static reflection. String to identifier transformation Reflection in C++Next struct foo { int bar; }; constexpr const char* bar_name = get_base_name_v<$reflect(foo::bar)>; int get_???bar_name???(const foo&);
  • 42. P0194R3: Static reflection. String to identifier transformation Reflection in C++Next struct foo { int bar; }; constexpr const char* bar_name = get_base_name_v<$reflect(foo::bar)>; int $identifier(ct_concat(“get_”, bar_name))(const foo&);
  • 43. P0194R3: Static reflection. String to identifier transformation Reflection in C++Next struct foo { int a; double b; string c; }; struct soa_foo { vector<int> as; vector<double> bs; vector<string> cs; };
  • 44. P0194R3: Static reflection Reflection in C++Next • supported: - variables; - data members; - member types; - enumerators; - template instantiations; - aliases
  • 45. P0194R3: Static reflection Reflection in C++Next • not supported: - declarations in namespaces (except for types); - functions (yet); - class templates (yet)
  • 46. P0194R3: Static reflection. Pros and cons Reflection in C++Next • Pros: - reflection of different entities is supported; - very lazy instantiation, only queried data is instantiated; - “you don’t pay for what you don’t use” at compile-time; - a good base for building higher-level and domain-specific libraries; - very extensible
  • 47. P0194R3: Static reflection. Pros and cons Reflection in C++Next • Cons: - awkward and verbose usage; - no attribute ideas
  • 48. A design for static reflection (P0590R0) Reflection in C++Next by Andrew Sutton, Herb Sutter
  • 49. P0590R0: A design for static reflection Reflection in C++Next • core-language changes: - operator $x; - where x is an id-expression; - returns a unique object of a generated type for an entity x; - the object represents its meta information; - you operate on these objects by calling member-functions • library changes: - std::meta::reflection_type<X>
  • 50. P0590R0: A design for static reflection. Simple example Reflection in C++Next std::string person = "John"; auto person_m = $person; static_assert(std::meta::is_variable_v< decltype(person_m)>); std::cout << person_m.name();
  • 51. P0590R0: A design for static reflection. Simple example Reflection in C++Next std::string person = "John"; auto person_m = $person; static_assert(std::meta::is_variable_v< decltype(person_m)>); std::cout << person_m.name(); auto type_m = person_m.type(); static_assert(std::meta::is_type_v<decltype(type_m)>);
  • 52. P0590R0: A design for static reflection. Simple example Reflection in C++Next std::string person = "John"; auto person_m = $person; static_assert(std::meta::is_variable_v< decltype(person_m)>); std::cout << person_m.name(); auto type_m = person_m.type(); static_assert(std::meta::is_type_v<decltype(type_m)>); using real_type = ???;
  • 53. P0194R3 vs P0590R0 Enum-to-string Reflection in C++Next template <class Enum> std::string to_string(Enum e) { using namespace std::reflect; using e_m = $reflect(Enum); static_assert(std::reflect::Enum<e_m>()); std::string result; for_each<get_enumerators_t<e_m>>([&](auto m) { using en_m = decltype(m); if (get_constant_v<en_m> == e) result = get_base_name_v<en_m>; }); return result; }
  • 54. P0194R3 vs P0590R0 Enum-to-string Reflection in C++Next template <class Enum> std::string to_string(Enum e) { using namespace std::meta; auto e_m = $Enum; static_assert(std::meta::is_enum_v<decltype(e_m)>); std::string result; for_each(e_m.enumerators(), [&](auto m) { if (m.value() == e) result = m.name(); }); return result; }
  • 55. P0194R3 vs P0590R0 Enum-to-string Reflection in C++Next template <class Enum> std::string to_string(Enum e) { using namespace std::meta; auto e_m = $Enum; static_assert(std::meta::is_enum_v<decltype(e_m)>); std::string result; for (auto e: e_m.enumerators()) if (m.value() == e) result = m.name(); return result; }
  • 56. P0194R3 vs P0590R0 Generic equal Reflection in C++Next template <class T> bool generic_equal(const T& a, const T& b) { bool result = true; for (auto member: $T.member_variables()) { auto ptr = member.pointer(); result &= a.*ptr == b.*ptr; } return result; }
  • 57. P0590R0: A design for static reflection. Pros and cons Reflection in C++Next • Pros: - reflection of different entities is supported; - better syntax; - a good base for building higher-level and domain-specific libraries; - extensible
  • 58. P0590R0: A design for static reflection. Pros and cons Reflection in C++Next • Cons: - some extra data may still be instantiated by compiler; - no attribute ideas
  • 59. Thank you for your attention! Reflection in C++Next