在扣除C++14中的"auto"之前使用"auto func(int)"
Use of 'auto func(int)' before deduction of 'auto' in C++14
我使用C++14
在GCC中编译了以下程序。
#include <iostream>
using namespace std;
auto func(int i);
int main()
{
auto ret = func(5);
return 0;
}
auto func(int i)
{
if (i == 1)
return i;
else
return func(i-1) + i;
}
但是,我会收到以下错误。
In function 'int main()': 8:16: error: use of 'auto func(int)' before deduction of 'auto' auto ret = func(5);
那么,我在这里缺少什么?
这是[dcl.spec.auto/11]:
如果需要具有未支配占位符类型的实体的类型 为了确定表达式的类型,该程序是不形成的。 一旦在函数中看到了未透露的返回语句, 但是,从该语句中得出的返回类型可以在 其余功能,包括其他返回语句。 [示例:
auto n = n; // error, n's type is unknown auto f(); void g() { &f; } // error, f's return type is unknown auto sum(int i) { if (i == 1) return i; // sum's return type is int else return sum(i-1)+i; // OK, sum's return type has been deduced }
- 结束示例]
要将其翻译成英语:编译器需要了解返回类型,然后才能使用该函数。如果像这样使用的auto
,这通常是通过在使用点之前移动定义来实现的。如果您实际上不需要使用返回类型扣除额,则可以在使用声明中提供签名(包括返回类型(后使用定义。
clang对此有更好的错误消息:
main.cpp:8:16: error: function 'func' with deduced return type cannot be used before it is defined
auto ret = func(5);
^
我想这是不言自明的。
当auto
用作不使用尾随返回类型语法的函数声明中的返回类型时,关键字 auto
表示返回类型将从其返回的操作数中推导陈述。这意味着在函数func()
的定义之前,不能执行扣除,但在此之前已在main()
中使用。
您可以在main()
之前移动定义,或使用Tailting返回类型语法来指定声明上的返回类型。
在您的示例中,实际上没有理由不能仅在 main()
之前移动函数的实现:
#include <iostream>
using namespace std; // you should avoid this, too
auto func(int i)
{
if (i == 1)
return i;
else
return func(i-1) + i;
}
int main()
{
auto ret = func(5);
return 0;
}
否则您无法使用自动关键字。特别是,您不能在不返回任何内容的递归功能中使用自动。您必须使用void
。这适用于lambda函数。例如:
int main()
{
auto f = [](int i)
{
// ... do something with `i` ...
if(i > 0)
{
f(i - 1); // <-- same error here
}
}
auto ret(func(5));
return 0;
}
呼叫f(i - 1)
有问题。要修复它,您必须通过实际类型替换auto
:
int main()
{
typedef std::function<void(int)> func_t;
func_t f = [](int i)
{
...
如果您确实想要一个功能,该函数无论如何都需要使用模板,而不是auto
。这实际上只是为了帮助您减少键入,而不是允许"任何类型"的方法。
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如何在自定义类中启用'auto loops'?
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 表观调用前面的表达式必须具有指向 func 类型的指针
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 擦除许多矢量元素,同时使用'auto'
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 推理类型如何工作"auto"和按引用调用?
- 'auto *x = new some_struct{};"是一个未初始化的变量?
- 为什么 std::gcd/lcm 返回 std::common_type_t<M, N> 而不是 auto?
- 将函数参数类型声明为 auto
- 不能在 if 语句 - c++ 中使用 void func 直接将字符串转换为大写
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 为什么 const auto &p{nullptr} 在 C++17 中不起作用,而 auto *p{nullptr} 不起作用?
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 使用"auto"推断嵌套初始值设定项列表的类型
- 在扣除自动之前使用decltype(auto) <func>
- 在扣除C++14中的"auto"之前使用"auto func(int)"