sharkdp/dbg-macro

[help]dbg with lambda

westfly opened this issue · 1 comments

As you may know, some times dbg expression may be an proc of lamda showing as below

int factorial(int n) {
  if (dbg(n <= 1)) {
    return dbg(1);
  } else {
    return dbg([&](){ printf("%d\n", n);
      return n * factorial(n - 1);
    }());
  }
}

but compiler report an error

main.cpp:9:16: error: lambda expression in an unevaluated operand
    return dbg([&](){

so I make a compromise to make compiler happy

int factorial(int n) {
  if (dbg(n <= 1)) {
    return dbg(1);
  } else {
    auto a = [&](){
      printf("%d\n", n);
      return n * factorial(n - 1);
    };
    return dbg(a());
  }
}

Is there a solution to avoid the stack variable when DBG_MACRO_DISABLE is true

Thank you for reporting this.

Here is a smaller example to reproduce this:

dbg([]() { return 42; }());

This does actually compile and work if DBG_MACRO_DISABLE is set. However, as you noticed, it does not compile if the dbg macro is enabled. I get:

error: lambda-expression in unevaluated context only available with ‘-std=c++2a’ or ‘-std=gnu++2a’

The problem is that we use decltype(…) on the expression inside of dbg(…)

#define dbg(...)                                                     \
  dbg_macro::DebugOutput(__FILE__, __LINE__, __func__, #__VA_ARGS__) \
      .print(dbg_macro::type_name<decltype(__VA_ARGS__)>(), (__VA_ARGS__))

This leads to the "in unevaluated context" error because lambdas are not allowed in unevaluated contexts.

This will actually work with C++20, but I don't know how to fix this for older versions. It would be great if we could at least generate a proxy type (dbg_macro::NoTypeAnnotation) if decltype(…) fails.