自动返回功能和模板实例化

auto-returning functions and template instantiation

本文关键字:实例化 功能 返回      更新时间:2023-10-16

编写一些模板代码时,我遇到了<unresolved overloaded function type>错误,可以简化为以下。

template <int N>
auto bar()
{
    return N;
}
int main(int, char* [])
{
    auto foo = [] (auto func) {
            return func();
        };
    foo(bar<3>);
}

错误是:

unresolved_overload.cpp: In function 'int main(int, char**)':
unresolved_overload.cpp:26:28: error: no match for call to '(main(int, char**)::<lambda(auto:1)>) (<unresolved overloaded function type>)'
     std::cout << foo(bar<3>) << std::endl;
                            ^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> constexpr main(int, char**)::<lambda(auto:1)>::operator decltype (((const main(int, char**)::<lambda(auto:1)>*)((const main(int, char**)::<lambda(auto:1)>* const)0))->operator()(static_cast<auto:1&&>(<anonymous>))) (*)(auto:1)() const
     auto foo = [] (auto func) {
                             ^
unresolved_overload.cpp:21:29: note:   template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note:   couldn't deduce template parameter 'auto:1'
     std::cout << foo(bar<3>) << std::endl;
                            ^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> main(int, char**)::<lambda(auto:1)>
     auto foo = [] (auto func) {
                             ^
unresolved_overload.cpp:21:29: note:   template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note:   couldn't deduce template parameter 'auto:1'
     std::cout << foo(bar<3>) << std::endl;

如果我们用显式返回类型int替换自动返回,则该示例会罚款。

为什么自动回报会遇到这些问题?我研究了模板论点推论和替代,但搜索基本上是没有结构的。我认为这可能与模板实例化的顺序有关,但对此没有太多意义...

每个安迪格的建议,我在GCC的错误列表上发现了同样的问题。Bug64194。首次在2014年报告。因此,结论似乎是GCC错误,值得庆幸的是,不是模板的另一个特殊情况。

解决此问题只需要有其他内容来触发实例(例如,分配给变量,using声明(。

尝试以下:

template <typename func>
auto bar(func&& f)->decltype(f())
{   
    return f();
}

int main()
{
    int i = 100;
    auto f = [=]()
    {
      return i;
    };
    bar(f);
    return 0;
 }