All, I am trying to write a lambda function that accepts all local variables by reference and iterates over them to print out the variable name and variable value. Or is this even possible?
I know with rtti I can get the individual members of a struct, but what I want is to get all in-scope members so that if I add a new var called int myNewVar
, the lambda will automatically capture it and print its type and value.
#include <iostream>
#include <string_view>
template <typename T>
constexpr auto type_name() noexcept {
std::string_view name, prefix, suffix;
#ifdef __clang__
name = __PRETTY_FUNCTION__;
prefix = "auto type_name() [T = ";
suffix = "]";
#elif defined(__GNUC__)
name = __PRETTY_FUNCTION__;
prefix = "constexpr auto type_name() [with T = ";
suffix = "]";
#elif defined(_MSC_VER)
name = __FUNCSIG__;
prefix = "auto __cdecl type_name<";
suffix = ">(void) noexcept";
#endif
name.remove_prefix(prefix.size());
name.remove_suffix(suffix.size());
return name;
}
int main()
{
int var1 {1}, var2 {2}, var3{3};
float f1 {1.1f}, f2 {2.2f};
char letter {'a'};
auto myLambdaThatCapturesEverythingLocal= [=] {
//For Each Variable that is in scope
std::cout << "Type is: " << type_name(varIter) << "\n";
//where varIter is a specific variable that is in scope, print its value.
std::cout << "Value is: " << varIter << std::endl;
};
myLambdaThatCapturesEverythingLocal();
/*
myLambdaThatCapturesEverythingLocal should print out
Type is: int
Value is: 1
Type is: int
Value is: 2
Type is: int
Value is: 3
Type is: float
Value is: 1.1
Type is: float
Value is: 2.2
Type is: char
Value is: a
*/
return 0;
}
Aucun commentaire:
Enregistrer un commentaire