首页 > 解决方案 > 用于捕获所有局部变量并对其进行迭代的 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;
}

标签: c++lambdareflectionmetaprogrammingtelemetry

解决方案


推荐阅读