c++ - 用于捕获所有局部变量并对其进行迭代的 Lambda 函数
问题描述
总而言之,我正在尝试编写一个 lambda 函数,它通过引用接受所有局部变量并遍历它们以打印出变量名称和变量值。或者这甚至可能吗?
我知道使用 rttr 我可以获取结构的各个成员,但我想要的是获取所有范围内的成员,这样如果我添加一个名为 var 的新int myNewVar
变量,lambda 将自动捕获它并打印它的类型和值。
#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;
}
解决方案
推荐阅读
- django - 获取错误 DecimalFields 必须定义一个 'max_digits' 属性
- python - 添加两个带孔的阵列以填充另一个阵列中的孔
- node.js - 搜索具有特殊字符的字符串
- javascript - 如何使用 Execute Javascript 关键字单击 Robot Framework 中的元素
- php - Laravel ::当分页时,长度未定义
- java - Javax Cache 'put' 的 SQL 等效项(INSERT 或 UPDATE)
- selenium - 由于存在另一个标签,无法从 selenium 的跨度中捕获文本
- c++ - 清理后没有编译
- php - 是否可以在 Laravel 中多次使用传递的参数?
- php - drupal 9中的主题信息