简体   繁体   中英

How to pass an initializer list as a function argument?

Basically, I'm looking to do something like this:

HANDLE hThread1 = CreateThread(...);
HANDLE hThread2 = CreateThread(...);
HANDLE hThread3 = CreateThread(...);

...

WaitForMultipleObjects( 3, {hThread1,hThread2,hThread3}, FALSE, INFINITE );

instead of this:

HANDLE hThread[3];
hThread[0] = CreateThread(...);
hThread[1] = CreateThread(...);
hThread[2] = CreateThread(...);

...

WaitForMultipleObjects( 3, hThread, FALSE, INFINITE );

The only solution I've found is using std::initializer_list , but obviously WaitForMultipleObjects() doesn't doesn't accept an std::initializer_list

Write a wrapper, then.

DWORD wait_for_multiple_objects(
    std::initializer_list<HANDLE> handles,
    bool wait_all = false, DWORD time = INFINITE
) {
    return WaitForMultipleObjects(
        handles.size(), &*handles.begin(), wait_all, time
    );
}

Now you can do:

wait_for_multiple_objects({ handle1, handle2, handle3 });

This obviously requires C++11 compiler that supports initializer_list . std::vector<HANDLE> might be a better type for the argument if you expect to pass an already-existing one. Or a more generic iterator/range interface, but that's left as an exercise for the reader.

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