为什么即使给出模板参数,ptr_fun也会发现这种模糊不清?

Eva*_*ran 8 c++ ambiguity functor

所以,这里有一些基本代码说明了我的问题:

#include <functional>

int func(int x) {
    return x;
}

int func(int x, int y) {
    return x + y;
}

int main() {
    std::ptr_fun<int, int>(func);
}
Run Code Online (Sandbox Code Playgroud)

对于具有不同参数数量的函数,我们有2个重载.然后我尝试在仿函数中转换单个参数版本.当然,我遇到以下错误:

test.cc: In function 'int main()':
test.cc:13:29: error: call of overloaded 'ptr_fun()' is ambiguous
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4/bits/stl_function.h:437:5: note: candidates are: std::pointer_to_unary_function std::ptr_fun(_Result (*)(_Arg)) [with _Arg = int, _Result = int]
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4/bits/stl_function.h:463:5: note:                 std::pointer_to_binary_function std::ptr_fun(_Result (*)(_Arg1, _Arg2)) [with _Arg1 = int, _Arg2 = int, _Result = int]

我知道我可以投出func并完成它,但它让我想到为什么这是模棱两可的?这两个版本std::ptr_fun都没有模板定义中的默认参数,我已经明确地说过两个模板参数int.

实际上,如果我只是在模板实例化时间内执行编译器实际执行的操作,如下所示:

#include <functional>

int func(int x) {
    return x;
}

int func(int x, int y) {
    return x + y;
}

std::pointer_to_unary_function<int,int> my_ptr_fun (int (*f)(int)) {
  return std::pointer_to_unary_function<int,int>(f);
}

int main() {
    my_ptr_fun(func);
}    
Run Code Online (Sandbox Code Playgroud)

它编译得很好,不知怎的,模糊性消失了!任何人都有任何问题,为什么会这样?

Nod*_*ode 4

这是因为当您调用模板化函数时,您不必指定任何可以通过函数参数类型推断的模板参数。因此,调用std::ptr_fun<int, int>实际上并不指定std::ptr_fun您调用哪个重载,而是依赖于您作为解析参数传递的函数。由于您的func重载适合两种std::ptr_fun重载,因此存在歧义。

编辑:这是一个演示我的观点的示例 - 在Ideone上运行,它显示两个函数调用返回相同的类型。

#include <functional>
#include <iostream>
#include <typeinfo>

double func(int x) 
{
    return x;
}

int main() 
{
    std::cout << typeid(std::ptr_fun<int>(func)).name() << std::endl;
    std::cout << typeid(std::ptr_fun<int, double>(func)).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)