【问题标题】:Ambiguous call to a function对函数的模糊调用
【发布时间】:2010-12-01 17:00:10
【问题描述】:

我有四个功能:

template<class Exception,class Argument>
 void allocate_help(const Argument& arg,Int2Type<true>)const;

 template<class Exception,class Argument>
 std::nullptr_t allocate_help(const Argument& arg,Int2Type<false>)const;

 template<class Exception>
 void allocate_help(const Exception& ex,Int2Type<true>)const;

 template<class Exception>
 std::nullptr_t allocate_help(const Exception& ex,Int2Type<false>)const;

但是当我打电话时:

allocate_help<std::bad_alloc>(e,Int2Type<true>()); //here e is of a std::bad_alloc type 

我收到一个错误:
错误 3 错误 C2668:对重载函数的模糊调用 为什么?

【问题讨论】:

    标签: c++ overloading


    【解决方案1】:

    因为你的电话同时匹配:

    template<class Exception,class Argument>
     void allocate_help(const Argument& arg,Int2Type<true>)const;
    

    使用Exception = std::bad_allocArgument = std::bad_allocArgument 会自动推导出来),并且:

    template<class Exception>
     void allocate_help(const Exception& ex,Int2Type<true>)const;
    

    Exception = std::bad_alloc。因此调用的模棱两可。

    另外我认为你的编译器应该在错误行之后输出所有匹配的函数,这样你就可以自己回答你的问题了。

    【讨论】:

      【解决方案2】:

      因为他们是模棱两可的。

      template<class Exception,class Argument>
      std::nullptr_t allocate_help(const Argument& arg,Int2Type<true>)const;
      
      template<class Exception>
      std::nullptr_t allocate_help(const Exception& ex,Int2Type<true>)const;
      

      第二个函数的签名是第一个函数的子集,这意味着在函数调用的上下文中,它们与将“任何类型”作为第一个参数并将 Int2Type 作为第二个参数相同。

      allocate_help<std::bad_alloc>(e,Int2Type<true>());
      

      可以成为:

      std::nullptr_t allocate_help<std::bad_alloc, std::bad_alloc>(const std::bad_alloc& arg,Int2Type<true>)const;
      

       std::nullptr_t allocate_help<std::bad_alloc>(const std::bad_alloc& ex,Int2Type<true>)const;
      

      编译器会如何选择?

      【讨论】:

      • +1,但它们没有完全相同的签名,第二个版本是第一个版本的子集,其中类型 ExceptionArgument 相同。模板参数Exception 和函数调用的第一个参数的类型不会有歧义的任何调用。
      • Int2Type&lt;true&gt; 如何匹配Int2Type&lt;false&gt;
      • 它没有。它们是完全不同的类型,不相关。 @ronag 发布的答案不正确。
      • @John:这正是我所暗示的!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2011-12-12
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多