【问题标题】:why does ptr_fun find this ambiguous even when template parameters are given?为什么即使给出了模板参数,ptr_fun 也会觉得这个模棱两可?
【发布时间】:2011-07-11 20:50:33
【问题描述】:

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

#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);
}

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

test.cc:在函数'int main()'中: test.cc:13:29:错误:重载“ptr_fun()”的调用不明确 /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4/bits/stl_function.h:437:5:注意:候选人是:std::pointer_to_unary_function std::ptr_fun(_Result (*)(_Arg)) [其中 _Arg = int,_Result = int] /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4/bits/stl_function.h:463:5:注意:std::pointer_to_binary_function std::ptr_fun(_Result (*) (_Arg1, _Arg2)) [其中 _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);
}    

它编译得很好,不知何故歧义消失了!有人知道为什么会这样吗?

【问题讨论】:

    标签: c++ functor ambiguity


    【解决方案1】:

    这是因为当你调用一个模板函数时,你不必指定任何模板参数,这些参数可以通过函数参数的类型来推断。因此,调用std::ptr_fun&lt;int, int&gt; 实际上并没有指定您调用的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;
    }
    

    【讨论】:

    • 嗯,我想我跟着。编译器正在尝试 2 模板参数版本 (Arg,Ret) 和 3 参数版本 (Arg,Arg,Ret) 并尝试将我的 &lt;int,int&gt; 匹配为 2 Args 并尝试推断 Ret?
    • @Evan - 是的,这就是我想说的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2011-08-01
    相关资源
    最近更新 更多