I’m beginning to learn Juce and have som knowledge about c++ and I wonder about the code pattern with the this reference in brackets. What do the brackets mean?
frequencySlider.onValueChange = [this] { targetFrequency = frequencySlider.getValue(); };
Found for example in this tutorial:
Sine synth
Look up lambdas in C++. That line defines a function which uses the current object (this) inside the function body.
1 Like
You are seeing a lambda here. A lambda can be compared to a free function, but instead of a regular function you can declare it inside a function body and make it access variables that are available in this context. To specify what should be accessible to a lambda the so called capture list is used – here the this
pointer of a class is captured, allowing you to access member variables and functions of the class in which the lambda is created.
Example:
void printFreeFunction (int value)
{
std::cout << value << std::endl;
}
class Foo
{
public:
Foo (const juce::String& n) : name (n) {}
void bar()
{
// Let's print a number to the console using our free function above
printFreeFunction (42);
// We need a printing function that adds the name of this instance to the output, let's declare a
// lambda for this
auto printLambda = [this] (int value)
{
std::cout << value << " from " << name.toRawUTF8() << std::endl;
}
// We can call our lambda just like a function. But in contrast to the free function above, it has
// access to the "name" value of this special class.
printLambda (42);
}
private:
const juce::String name;
}
3 Likes
Ok, lambdas I’m a bit familiar with from Python so I see how that works here. Thanks.
However, (comparing a bit with Python) in this example I don’t see why [this]
is needed. Isn’t 42 passed as an argument regardless? Perhaps if value
was a property of Foo it would make more sense? Or am I missing some detail?
In that example, the “this” is needed because name is a member of class Foo, and is used in the lambda. In your example, “this” is needed because frequencySlider is a member of the component in which that code exists.