自动返回功能和模板实例化
auto-returning functions and template instantiation
编写一些模板代码时,我遇到了<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;
}
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- 模板功能的实例化
- 超载分辨率在模板实例化点后找到功能
- 模板功能不使用RVALUE参考实例化/接收呼叫
- 自动返回功能和模板实例化
- 如何在不引起实例化的情况下获取功能模板的签名
- 模板功能实例化和专业化
- 使用合格类型实例化的模板内部功能的名称分辨率
- c++ 具有每个实例化对象特定功能的结构(或类)
- 运行时的模板实例化和功能选择
- 功能与安全/静态与动态实例化