繁体   English   中英

c ++:为什么在给出模板函数的所有类型参数时出现错误,但是在省略参数时可以?

[英]c++: why am I getting an error when giving all type parameters of a template function, but OK when omitting a parameter?

在下面带有参数包和ReturnType模板函数中,如果我省略最后一个参数ReturnType ,为什么编译器ReturnType ,而如果我明确给出最后一个类型参数,则给我一个错误(关于歧义)。

谢谢。

#include <functional>
using namespace std;

template<typename... Args, typename ReturnType>
auto make_function(ReturnType(*p)(Args...))
    -> std::function<ReturnType(Args...)> {
  return {p};
}

int foo1(int x, int y, int z) { return x + y + z;}
float foo1(int x, int y, float z) { return x + y + z;}

int main() {
  auto f0 = make_function<int,int,int>(foo1); //OK
  //auto f1 = make_function<int,int,int,int>(foo1); //not OK
  // test33.cpp:15:48: error: no matching function for call to 
  // 'make_function(<unresolved overloaded function type>)'
  return 0;
}

感谢Xeo。

在参数包之后放置参数是强制扣除的特殊情况。 您无法为ReturnType显式提供参数。 因此,它寻找foo1( int, int, int, int )并找不到任何东西。

顺便说一下,如果你想击败演绎,一个技巧是通过获取函数的地址来隐藏参数列表: (&make_function<int,int,int,int>)(foo1) 这导致Clang特别抱怨

候选模板被忽略:无法推断模板参数'ReturnType'

并且ICEs GCC(但仍然打印指向右侧的诊断)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM