c++:为什么在提供模板函数的所有类型参数时出现错误,但在省略参数时正常?

标签 c++ templates

在以下带有参数包和 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 专门提示

candidate template ignored: couldn't infer template argument 'ReturnType'

它 ICE GCC(但仍然打印指向正确行的诊断)。

关于c++:为什么在提供模板函数的所有类型参数时出现错误,但在省略参数时正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21744659/

相关文章:

c++ - 将帧号/索引添加到 AVFrame 对象

c++ - clang_complete 不完成构造函数

c++ - 这个容器实现是否完全明智?

c++ - 具有用户定义函数和 MPI_BOTTOM 的 Allreduce

c++ - 提高ofstream的性能

c++ - Visual Studio 2008,检测内存泄漏, undefined symbol '__FILE__'

c++ - C++ 中的虚函数和模板——它们可以被其他(C++ 中存在的)操作替换吗?

c++ - 在 It 是迭代器的 template<class It> 函数中,我可以使 It::value_type 同时适用于 vector::iterators 和 array::iterators 吗?

c++ - 来自不同类型的模板类复制构造函数 : should it follow the Rule of Five?

templates - 通过函数指针函数将lambda作为模板参数传递给模板