【发布时间】:2023-04-06 13:13:02
【问题描述】:
根据这个问题的第一个答案:function template overloading,一个 “非模板化(或“较少模板化”)的重载优先于模板”。
#include <iostream>
#include <string>
#include <functional>
void f1(std::string const& str) {
std::cout << "f1 " << str << "\n";
}
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 << "\n";
};
call(f1, "Hello World!");
call(f2, "Salut Monde !");
return 0;
}
据我了解,call 的第二个定义是“非模板化”,因此当我执行 call(f1, "1") 或 call(f2, "2") 时应该选择第一个定义。
事实并非如此,我得到以下输出:
f1 Hello World!
f2 Salut Monde !
如果我删除 call 的模板版本,我会得到预期的输出。
在这种情况下,为什么我的 call 重载没有选择第一个?
【问题讨论】:
-
只有当参数类型完全匹配时才首选非模板。在您链接到的线程中,请注意
10匹配非模板但10u匹配模板的示例。
标签: c++ templates c++11 overload-resolution