Home > Software design >  How can i implicity declare function template's argument if one of the arguments is another fun
How can i implicity declare function template's argument if one of the arguments is another fun

Time:12-07

i have a template function that looks like this:

template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>

and im trying to call it like so

pool.enqueue<void,TCPServer,ReceivedSocketData,std::unordered_map,std::mutex>(serverThreadFunction, &server, receivedData,topicsData,&allDataLock);

however it gives me the error C

no instance of function template matches the argument list  
argument types are: (void (TCPServer *server, ReceivedSocketData &&data,
 std::unordered_map<std::string, topic, std::hash<std::string>, std::equal_to<std::string>,
 std::allocator<std::pair<const std::string, topic>>> &map, 
std::mutex *lock), TCPServer *, ReceivedSocketData, std::unordered_map<std::string, topic, std::hash<std::string>, 
std::equal_to<std::string>, std::allocator<std::pair<const 
std::string, topic>>>, std::mutex *)            object type is: ThreadPool

i assume the issue is I dont know how to explicitly declare types for the arguments who's type can't be assessed. Aside from that i'm not sure why it doesn't work.

CodePudding user response:

Simply call it as

pool.enqueue(serverThreadFunction, &server, receivedData, topicsData, &allDataLock);

Template arguments can be deduced from function argument/parameter pairs. In particular if the function template uses a template parameter as a forwarding reference (e.g. F in F&& or Args in Args&&), then not specifying the corresponding template argument and letting it be deduced is the only sensible and expected use.

Template arguments should usually only be specified explicitly for template parameters that aren't used in a type of a function parameter.


Additionally, based purely on the types mentioned in the error message, serverThreadFunction has a rvalue reference to ReceivedSocketData parameter and so won't accept a lvalue argument (such as receivedData) for it. Pass it a rvalue instead.

  • Related