简体   繁体   中英

How can I access std::function in std::list in C++

I am attempting to answer generate a Template function in C++ which takes in an std::list of std::function (I think). I am however not sure how to understand the datatype I am working with.

According to GDB my datatype is:

type = std::__cxx11::list<std::function<void(std::array<positions, 3>&)>, std::allocator<std::function<void(std::array<positions, 3>&)> > > (*)(const std::array<positions, 3> &)

I can not access the element as an array if I call the input movenents I can not access for example the first element as movement[0] I don't understand why that is since the type looks like a list.

I have tried to access it as an array, and I have tried to read std::list containing std::function and access it with:

for (auto f: movements) {
        (*f)();
    }

The function generating the the list looks like this:

auto movements(const pieces_positions &pieces) {
    auto result = std::list<std::function<void(pieces_positions&)>>{};
    for (auto i=0u; i<pieces.size(); ++i)
        switch(pieces[i]) {
            case positions::pos1:
                result.push_back([i](pieces_positions& pieces){ pieces[i] = positions::pos2; });
                break;
            case positions::pos2:
                result.push_back([i](pieces_positions& pieces){ pieces[i] = positions::pos1; });
                result.push_back([i](pieces_positions& pieces){ pieces[i] = positions::pos3; });
                break;
            case positions::pos3:
                result.push_back([i](pieces_positions& pieces){ pieces[i] = positions::pos2; });
                break;
        }
    return result;
}

Two things (that I think are what you're asking about):

  1. The symbol movements is a function that you need to call. You do it by the usual movements(pices) .

  2. The function objects in the list that the function returns are not pointers that can be dereferenced. You use them as normal functions and call them as such, like f(pieces) .

Also, in C++ there's no standard "array-list" like container. A list is a list and can't be indexed like an array or a vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM