Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deduction in template functions with few args (C++17)

I have few instances of one template function. Each of them sequentially executes each of given lambdas, accompanying them with specific messages. When I do that with one lambda, everything works fine, but when I try to add more than one, I get

note: candidate template ignored: deduced conflicting types for parameter 'Task'

from Clang. Here is my code:

template <class Task>
void doTasks(Task task1) {   //works fine
    if (std::__is_invocable<Task>::value) {
        std::cout << "doing first task" << endl;
        task1;
    }
}

template <class Task>
void doTasks(Task task1, Task task2) { //deduced conflicting types
    if (std::__is_invocable<Task>::value) {
        std::cout << "doing first task" << endl;
        task1();
        std::cout << "doing second task" << endl;
        task2();
    }
}

int main(){
    doTasks([&] (){std::cout << "1" << endl;}); 

    doTasks([&] (){std::cout << "1" << endl;},
            [&] (){std::cout << "2" << endl;}); 
  
    return 0; 
}

What’s wrong with it? How can I deal with my problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sorry if it’s a stupid question, I’m some kind of a beginner in C++ and may not understand some template nuances.

>Solution :

The lambdas are of different types. You need to add another template parameter for the second one:

#include <type_traits> // for the proper `std::invocable`

template <class Task, class AnotherTask>
void doTasks(Task task1, AnotherTask task2) {
    if constexpr (std::is_invocable_v<Task> && std::is_invocable_v<AnotherTask>) {
        std::cout << "doing first task\n";
        task1();
        std::cout << "doing second task\n";
        task2();
    }
}

Note: Since it’s C++17, you can also use constexpr if to deal with the if at compile time only.

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading