【问题标题】:why the template argument deduction/substitution failed in the code?-为什么代码中的模板参数扣除/替换失败?-
【发布时间】:2019-04-26 11:05:37
【问题描述】:

我正在使用编译器 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);
}

帮我理解错误...

【问题讨论】:

  • 请注意,您依赖的是 gcc 扩展。对于函数参数,C++14 没有 auto 这样的特性(即将这些函数转换为模板函数,每个 auto 都有一个模板参数)。这是具有相同错误但没有 auto 的等效版本:godbolt.org/z/miMZ3r

标签: c++ templates gcc


【解决方案1】:
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);
    }
    

【讨论】:

  • 将 f 和 f1 更改为 - auto f(int a){return a;} & int f1(int (*g)(auto),int a) {return g(a);} 和没有显示错误。我没有看到“您不能获取模板的地址”是问题所在。如果你能再澄清一下....../*对不起,它在 cmets 中没有显示 '\n'*/
  • auto f(int a){return a;} 不是模板。相当于int f(int a){return a;}
  • 好吧,我错了。谢谢。
猜你喜欢
  • 2013-06-20
  • 2019-09-11
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多