InterviewSolution
| 1. |
Can You Create A C++11 Thread With A Function Pointer That Takes A Bunch Of Arguments? |
|
Answer» Yes ! You can just PASS the function arguments to the thread constructor. The thread constructor is a variadic template, which means it can accept any number of arguments. Here's an EXAMPLE: #include "stdafx.h" #include <string> #include <thread> #include <IOSTREAM> using namespace std; void FireTorpedo(int numCities, string torpedoType) { cout << "FIRING torpedo " << torpedoType << " at" << numCities << " cities." << endl; } int main() { thread t1(FireTorpedo, 3, "HungryShark"); t1.join(); return 0; } Yes ! You can just pass the function arguments to the thread constructor. The thread constructor is a variadic template, which means it can accept any number of arguments. Here's an example: #include "stdafx.h" #include <string> #include <thread> #include <iostream> using namespace std; void FireTorpedo(int numCities, string torpedoType) { cout << "Firing torpedo " << torpedoType << " at" << numCities << " cities." << endl; } int main() { thread t1(FireTorpedo, 3, "HungryShark"); t1.join(); return 0; } |
|