Why is my function overloaded not preferable to my template?

According to the first answer to this question: overloading the function template , "templates are not preferred" (or "less template").

#include <iostream>
#include <string>
#include <functional>

void f1 (std::string const& str) {
    std::cout << "f1 " << str << std::endl;
}

template <typename Callback, typename... InputArgs>
void call (Callback callback, InputArgs ...args) {
    callback(args...);
}

void call (std::function<void(std::string const&)> callback, const char *str) {
    std::cout << "custom call: ";
    callback(str);
}

int main() {
    auto f2 = [](std::string const& str) -> void {
        std::cout << "f2 " << str << std::endl;
    };

    call(f1, "Hello World!");
    call(f2, "Salut Monde !");

    return 0;
}

Where, as I understand it, the second definition callis "not templated" and therefore should be chosen by the first when I do call(f1, "1")or call(f2, "2").

This is not so, I get the following output:

f1 Hello World!
f2 Salut Monde !

If I remove the template version call, I will get the expected result.

Why is my overload callnot selected in the first case in this case?

+4
source share
5

f1 f2 std::function, , , .

call, , :

void call (void(*callback)(std::string const&), const char *str)

f1.


: + ( )...

auto f2 = +[](std::string const& str) -> void
//        ^ unary +
+6

lambda f2 std::function<void(std::string const&)>, - . call .

+3

f1, f2 std::function<...>. .

( )

std::function<void(std::string const&)> f3(f2);
call(f3, "Salut Monde !");

.

+3

std:: function -, , -. :

call(f1, "Hello World!");
call(f2, "Salut Monde !");

, :

call(static_cast<std::function<void(std::string const&)>>(f1), "Hello World!");
call(static_cast<std::function<void(std::string const&)>>(f2), "Salut Monde !");

LIVE

+1

when you overload a function with a certain type (the second argument of the function), in this case when you call a function with a certain argument, the template function will not call, because you are already writing the function for a certain type. in addition to the specific type of calling the template function, the compiler task first selects a specific type argument, and then the template function

-1
source

All Articles