类成员上下文中的`auto`返回类型 [英] `auto` return type in context of class members

查看:185
本文介绍了类成员上下文中的`auto`返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将自动推论应用于班级成员?例如,以下代码

How can automatic type deduction be used for class members? For example, the following code

struct A
{
  auto foo(); // foo is defined in another file 
};


int main()
{
  A a;
  a.foo();
}

其中foo具有返回类型auto的结果导致以下错误:

where foo has the return type auto results in the following error:

error: function 'foo' with deduced return type cannot be used before it is defined
  a.foo();
    ^

该错误是可以理解的,因为在不知道其定义的情况下,编译器无法知道foo的返回类型.

The error is comprehensible since the compile cannot know what foo's return type is without knowing its definition.

我的问题是,如果有任何变通方法或某种编程模式来规避自动返回类型不能用于类成员函数的问题,那么该函数的声明和定义必须分开.

My question is, if there is any workaround or some kind of programming pattern to circumvent the problem that auto return type cannot be used for class member functions, in case that the function's declaration and definition is separated.

推荐答案

如果要使用返回类型推导,则不能将声明和定义分成不同的文件(除非每个人都包括).除了使用实际类型外,没有其他解决方法.

If you want to use return type deduction, you cannot separate the declaration and definition into different files (not unless everyone includes both). There's no workaround for this other than to use an actual type.

当C ++编译调用func的代码时,它必须能够在那时 知道它将返回什么.如果在该翻译单元中没有定义,则编译器将无法知道将返回什么.因此,编译器无法编译该代码.而且C ++的编译模型不允许它以这种方式使用来自其他翻译部门的信息.

When C++ goes to compile code that calls func, it must be able to know, at that time, what it will return. Without having definition in that translation unit, the compiler cannot know what will be returned. And therefore, the compiler cannot compile that code. And C++'s compilation model does not allow it to use information from other translation units in this way.

您可能要做的最好的事情就是等待模块,这也许可以解决这个问题.

The best you might be able to do is wait for modules, which may be able to get around this.

不要将返回类型推论视为永远不必编写返回类型的一种方式.此功能旨在用于以下情况:返回类型很难编写,最合理的写法是decltype(expr),而expr是要返回的确切表达式.这些情况通常在模板代码中进行,无论如何都必须将它们放入标头中.如果返回类型对您而言简单明了,那么没有什么理由 not 放在其中.默认情况下,请勿使用返回类型推导.

Don't think of return type deduction as a way to never have to write return types. It's a feature intended for circumstances where the return type is awkward to write, where the most reasonable way to write it is as a decltype(expr), and expr is the exact expression you're going to return. And those cases are typically in template code, which has to go into headers anyway. If the return type is simple and obvious to you, there's really little reason not to put it there. Don't use return type deduction by default.

这篇关于类成员上下文中的`auto`返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆