2

Question

When writing custom Natvis visualizations for Visual Studio, (how) can I access fields of a lambda wrapped in a std::function?

Concrete example

I have a class looks somewhat like this (very simplified):

class VariableVector {
public:
  // Constructor for returning values from captured vector
  Variable(const std::vector<double>& values)
    : m_valueGetter{[&values](int index) { return values[index]; }}
    {}
  
  // Constructor for always returning a constant value
  Variable(double value)
    : m_valueGetter{[value](int index) { return value; }}
    {}

  double operator[](int index) {
    return m_valueGetter(index);
  }
  
private:
  std::function<double(int)> m_valueGetter;
}

It uses a std::function to hide different implementations for how to get the values.

I now would like to display the values in the debugger using a custom .natvis file. As function calls are not allowed, I need to access the variables captured in the lambdas. How can I do that? This is the closest I could get:

<Type Name="VariableVector">
  <DisplayString>(*m_valueGetter._Mystorage._Ptrs[9])</DisplayString>
</Type>

It shows me e.g. {value: 42} in the debugger. In the raw view, this element has a _Callee member which has the value field. However,

<Type Name="VariableVector">
  <DisplayString>(*m_valueGetter._Mystorage._Ptrs[9])._Callee</DisplayString>
</Type>

already gives me an error.

If it's nothing too major, I could also change the structor of my VariableVector, but I need the type erasure...

1
  • 1
    Aside: Unless you have a typo, the first lambda has a dangling reference. values ceases to exist before you can use m_valueGetter Commented Nov 17, 2022 at 13:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.