C++ 自动返回函数和模板实例化

C++ 自动返回函数和模板实例化,c++,c++14,C++,C++14,在编写一些模板代码时,我遇到了错误,这些错误可以归结为以下几点 template <int N> auto bar() { return N; } int main(int, char* []) { auto foo = [] (auto func) { return func(); }; foo(bar<3>); } 模板 自动栏() { 返回N; } int main(int,char*[]) {

在编写一些模板代码时,我遇到了
错误,这些错误可以归结为以下几点

template <int N>
auto bar()
{
    return N;
}

int main(int, char* [])
{
    auto foo = [] (auto func) {
            return func();
        };

    foo(bar<3>);
}
模板
自动栏()
{
返回N;
}
int main(int,char*[])
{
自动foo=[](自动函数){
返回func();
};
富(巴);;
}
错误为:

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;
unresolved_重载.cpp:在函数“int main(int,char**)”中:
未解析的_重载。cpp:26:28:错误:对“(main(int,char**)::)()”的调用不匹配
std::cout试试这个:

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


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

    bar(f);

    return 0;
 } 
模板
自动栏(func&&f)->decltype(f())
{   
返回f();
}
int main()
{
int i=100;
自动f=[=]()
{
返回i;
};
巴(f);
返回0;
} 

根据AndyG的建议,我在GCC的错误列表中发现了相同的问题。2014年首次报道。因此,结论似乎是这是一个GCC错误,谢天谢地,不是模板的另一个特例


解决这一问题只需要有其他东西来触发实例化(例如,使用
声明分配给变量,

gcc无法编译显示的代码,报告此错误消息,但
auto z=bar;傅(z)
似乎工作得很好,这让我把矛头指向了编译器。编译也失败了。无论如何,我怀疑你不能这样做的原因和你不能做
转换(…,max)
的原因是一样的。您需要显式地强制转换所需的重载,或者将其包装在一个函子中。@user167921我并没有用Clang实际测试它,但godbolt表明它确实可以编译。您可以详细说明一下显式强制转换重载吗?在模板函数定义中使用decltype我认为这应该可以编译。从技术上讲,您应该使用
&bar
,但在gcc中没有区别。令人惊讶的是,它在MSVC 19.00.23506中编译。也在Clang 7.0中编译我感谢您的努力,但我不相信这能回答问题。我也不认为这是解决老年退休金问题的适当办法。