Syntax help: Function pointer surrounded by square brackets [duplicate] - c++11

This question already has answers here:
What is a lambda expression in C++11?
(10 answers)
Closed 4 years ago.
I'm confused about the use of square brackets around [funcParam] in the C++11 code segment below:
typedef std::function<std::vector<OtherType> ()> FuncPtr;
inline void create(FuncPtr funcParam)
{
auto create_evaluator = [funcParam] ()
{
return anotherFunction(funcParam());
};
// ...
}
The code above it called by this line (somewhat simplified to keep it readable):
create( [] () { return CONSTANT; } );
Can someone explain the use of brackets in both situations? In the calling code, it looks to be used to create a function without a name. What's it doing in the first segment? Thanks!

create_evaluator is a lambda expression (check out the examples at the bottom of that page).
In the case of
auto create_evaluator = [funcParam] ()
{
return anotherFunction(funcParam());
};
[funcParam] is a variable in the local scope that is captured by the lambda function and therefore available to be reference within the lambda function when it is called elsewhere.
() denotes the arguments to the lambda function (none in this case)
{ return anotherFunction(funcParam()); } is the body of the lambda function.
With the call
create( [] () { return CONSTANT; } );
create is called with another lambda expression as its argument. That lambda argument
captures nothing: []
has no arguments: ()
has the body: { return CONSTANT; }

Related

Unexpected Promise <state> pending being returned using axios [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm hoping somebody can point out the error of my ways here.
I have two functions at the moment. One is getData and it's an async function that simply makes an API call requesting data. The second function is getRandomCategories that encapsulates the getData function call and holds the value of that async operation in a variable called res. The rest of the code within getRandomCategories manipulates the response data to an array of numbers where each number represents a category.
When I use the debugger statement in the getRandomCategories function (right before the return statement within the try block) I'm getting the data type I'm expecting from my variable named apiCallCategoryArray - it's an array of numbers each representing a category. Life is good.
Here's the rub. When I call getRandomCategories expecting the dataArray variable (at the bottom of the code snippet) to hold an array of numbers - I'm getting a Promise back with its state pending??
I'm not understanding why the value for apiCallCategoryArray variable is showing up as my expected value using the debugger (and thus I'm returning it within the function) but I'm not able to access that value when I call the function. Why am I getting a Promise back with a pending state? What am I missing?
Here's my code below:
async function getData(endpoint, query, value) {
return await axios.get(
`http://jservice.io/api/${endpoint}?&${query}=${value}`
)
}
// createa a function that will return 6 random categories
async function getRandomCategories() {
try {
const res = await getData('categories', 'count', 50)
const data = res.data;
const categories = filterCategoryData(data); // I'm filtering for category id with clues_count === 5
const categoryIdArr = mapCategoryIds(categories); // an array of just category Ids
const shuffledCategoryIds = shuffle(categoryIdArr);
const apiCallCategoryArray = takeFirstXItems(shuffledCategoryIds, 6);
debugger// the value is what I'm expecting an array of numbers with length = 6
return apiCallCategoryArray
} catch (err) {
console.log(err);
}
}
//Solution one: Does not work. I'm getting a promise back instead of an array of numbers
const dataArray = getRandomCategories()
console.log(dataArray) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers
// Solution two: Does not work either. I'm still getttng a promise back instead of an array of numbers
const dataArray2 = getRandomCategories().then((array) => {
return array
})
console.log(dataArray2) // Promise { <state>: "pending" }
// expected return value [12231, 12344, 343245,124041, 12344, 348855] array of numbers
My objective is for my dataArray variable to hold an array of numbers (not a Promise with pending) returned by calling getRandomCategories(). So I can use this value for other functions in my code.
Thanks in advance for your time and responses.
you need to use use async, await to get back your Promise data. like this
async function test(){
let dataArray2 = await getRandomCategories();
console.log(dataArray2);
};

What is the syntax for an if-let statement?

I encountered this snippet in some example code. It works fine, but I got a linter error saying that it should be structured as an if-let statement.
match event {
glutin::Event::WindowEvent { event, .. } => match event {
glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
_ => (),
},
_ => ()
}
This was my attempt to restructure it:
if let _ = glutin::Event::WindowEvent { event, .. } {
match event {
glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
_ => (),
}
}
Oops, that's a syntax error. What would be the correct way to clear the linter warning?
After looking at the code more closely, I realized that I don't understand the syntax. glutin::Event::WindowEvent { event, .. } looks like the syntax for creating a new instance of WindowEvent but how can that be allowed inside a match statement?
Also, what does the .. mean? I'm familiar with ..Default::default(), but not the double dot by itself.
The syntax that eludes you is called destructuring.
This pattern allows to match certain fields in a struct, enum, or tuple. You therefore cannot just use if let with the destructuring on the right side of the binding.
The code you want is probably:
if let glutin::Event::WindowEvent { event, .. } = event {
match event {
glutin::WindowEvent::Closed => return glutin::ControlFlow::Break,
glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
_ => (),
}
}
There is a possible confusion between the right hand event variable and the one extracted from the pattern.
The use of event in the destructuring is made mandatory because it needs to use struct fields by name.
Directly quoting from The Book, second edition:
The if let syntax lets you combine if and let into a less verbose way to handle values that match one pattern and ignore the rest.
It also provides this example:
if let Some(3) = some_u8_value {
println!("three");
}
The correct syntax is if let «pattern» = «expression» { ... }, and not the opposite written in the question.
if let glutin::Event::WindowEvent { event, .. } = event {
// ...
}

Combining 'using' and 'reinterpret_cast'

I have a list of functions that are put in a table for lookup for an interpreter. I cast each function to void (*) () as follows:
using vptr = void (*) (); // cast to a function that takes no args, and returns no result
struct function date_funs[] =
{
{C_FN3, X_A3, "III", (vptr) do_hms_to_time, "hms_to_time"},
...
This works, and does exactly what I want. I wonder if there was another way of expressing it, like:
using vptr = reinterpret_cast<void(*) ()>;
The C++ compiler complains of a syntax error, though. Is there any way I can fix this, or should I just use the first form of vptr that I devised?
No.
using (in this context) defines a type alias. In your attempt, you are not giving a type, but have a partial expression, which is a syntax error.
To shorten usages, e.g. reinterpret_cast<void(*) ()>(do_hms_to_time), you could introduce a function as well as the using.
using vptr = void (*) ();
template <typename Func>
constexpr vptr to_vptr(Func && func)
{ return reinterpret_cast<vptr>(func); }
and use it
{C_FN3, X_A3, "III", to_vptr(do_hms_to_time), "hms_to_time"},

Referencing self in a callback

My code is:
class myclass observable.Observable
{
let label = "test";
navigatingTo(args: observable.EventData)
{
target.on( "name", this._callback );
}
_callback ( eventData )
{
console.log( this.label);
}
}
When I print out this.label in the callback - "this" object is not the object that I expect - which I think should be the myclass instance.
I've got a separate method for the callback because I'm also calling .off() later and need a reference to the method (as opposed to anonymous function)
You can pass a third argument when subscribing with on(). The third argument will be used as a context(this) for the callback. So probably you want to do:
target.on("name", this._callback, this);

pass function to another and call by name

<a id="aHw" href="#" callbackName="helloworld">test</a>
...
<script>
function helloworld() { alert('hello world'); }
</script>
...
question ; how can i produce callBack to pass another function
<script>
...
var cbName = $('#aHw').attr('callbackName');
foo( passfunction ); //How???
...
</script>
<script>
function foo(callBack)
{
callBack(); // call hello world.
}
</script>
thanks in advance.
A function in JavaScript is just an object.
The question(s) don't make terribly much sense to me, but consider the following:
function fn1 () {
alert("fn1")
}
function doIt(cb) {
cb()
}
// direct -- to show point in general
// fn1 evaluates to the function-object, which is then passed
doIt(fn1)
// lookups up fn1 by name, then passes that function-object
// the value "fn1" can be any arbitrary string, such as that which
// was stored in the attr:
// e.g. doIt(window[cbName])
doIt(window["fn1"])
// anon function to iterate sameness
// the anon function returns a new function-object
doIt(function () { alert("anon") })
Happy coding.
Ok. So to have an anchor do something on MouseOver, you'd use this code:
<a id="aHw" href="#" onmouseover="doSomething()">test</a>
You can pass a function to another function this way:
function callSomeFunction( fn )
{
fn();
}
callSomeFunction( alert );
Or you can pass an anonymous function to the above:
callSomeFunction( function(){ alert( "Finally! A message!" ); } );
If you're trying to pass the name of a function as a string (which is a fundamentally bad idea and a terrible risk and hard to debug and DON'T DO IT), then you can use eval:
function callNamedFunction( fn )
{
eval(fn)()
}
Or you might be able to get away with:
function callNamedFunction( fn )
{
(window[fn])()
}
foo( Function('return ' + cbName)() )
I think that's what your after..
But if it's in the browser, and you know that the callback is a global object, you could do..
foo(window[cbName])
Well, if nothing else helps, eval() will:
function foo( callBack ) {
eval( callBack + '()' );
}
If you know where the function is defined (e.g window, or custom namespace) you can invoke it by the string name. Otherwise you would have to eval (bad idea). Also, use data-attributes.
test
...
// invoke runs a function by name in the provided context, or window
function invoke(cbname, context){
return (context || window)[cbname].call();
}
// get attribute through the data method
var funcName = $('a').data('callback');
// run callback
var result = invoke(funcName);

Resources