c++ - 为什么模板参数推导/替换在代码中失败?-

标签 c++ templates gcc

我正在使用编译器 g++ 6.3.0 (c++14)。 在代码中-

#include<iostream>

int f(auto a){return a;}

int f1(auto (*g)(int),int a) {return g(a);}

main()
{
    std::cout<< f1(f,8);
}

编译器无法推断出 g 的返回类型。 它显示以下错误-

temp.cpp: In function 'int main()':
temp.cpp:9:20: error: no matching function for call to 'f1(<unresolved overloaded function type>, int)'
  std::cout<< f1(f,8);
                    ^
temp.cpp:5:5: note: candidate: template<class auto:2> int f1(auto:2 (*)(int), int)
 int f1(auto (*g)(int),int a) {return g(a);}
     ^~
temp.cpp:5:5: note:   template argument deduction/substitution failed:
temp.cpp:9:20: note:   couldn't deduce template parameter 'auto:2'
  std::cout<< f1(f,8);
                    ^

但是代码没有报错-

#include<iostream>

int f(int /* <<<<< */ a){return a;} // only (auto a) is changed to (int a)

int f1(auto (*g)(int),int a) {return g(a);}

main()
{
    std::cout<< f1(f,8);
}

帮助我理解错误...

最佳答案

int f(auto a){return a;}

相当于

template <typename T>
int f(T a){return a;}

您不能获取模板(或重载集)的地址 - 这就是您看到该错误的原因。解决方法:

  • 取你要实例化的地址:

    return f1(f<int>,8);
    
  • 使 f1 接受 auto 并传递一个 lambda:

    int f1(auto g, int a) {return g(a);}
    
    int main()
    {
        std::cout<< f1([](auto x){ f(x); },8);
    }
    

关于c++ - 为什么模板参数推导/替换在代码中失败?-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866274/

相关文章:

c++ - OpenCV 无法获得 Mat 的正确最大值和最小值

c++ - 在 C++ Vector 中存储从类模板继承的类

gcc - 无法编译程序集 :/usr/bin/ld: i386 architecture of input file `array1.o' is incompatible with i386:x86-64 output

c++ - Clang 上的重载运算符歧义,但 GCC 上没有,哪个是正确的?

c++ - 声明未声明的全局变量

C++:无法将 'float (*)()' 转换为 'float'

javascript - 直方图均衡化(图像 Javascript 初学者)

c++ - 无法将参数 1 从 'Component<W> *' 转换为 'Component<W> *'

C++ 模板 - 错误 : expected initializer before '<' token

c - 无法在eclipse juno中编译C