Search code examples
c++templatesvariadic-templates

Template deduction on function with variadic template arguments


I am trying to write a sort of task graph. When I emplace new Tasks I want to be able to add a varying amount at once and get a tuple that contains a handle for each added task.

I have written a base case for one task and overload with variadic template arguments that calls the base case.

template<typename Task>
node<Task> emplace(Task&& task) {
  return node<Task>{std::move(task)};
}

template <typename... Tasks, std::enable_if_t<(sizeof...(Tasks) > 1)>>
auto emplace(Tasks&&... tasks) {
  return std::make_tuple(emplace(std::forward<Tasks>(tasks))...);
}

When I now emplace with one task like

emplace([](){ something cool; });

I get no error but when I add two or more tasks

emplace(
  [](){ task a; },
  [](){ task b; }
);

I get an error saying that template argument deduction/substitution failed


Solution

  • std::enable_if_t<(sizeof...(Tasks) > 1)> is just void (when it exists). So your template is template <typename... Tasks, void> whatever. So you have a non-type template parameter of type void. Good luck matching it.

    What you actually want instead is typename = std::enable_if_t<(sizeof...(Tasks) > 1)>, a type template parameter with a default value which may or may not be SFINAEd out.