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

查看:31
本文介绍了类成员上下文中的 `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 是准确的你要回来的表情.这些情况通常在模板代码中,无论如何都必须进入标题.如果返回类型对您来说是简单明了的,那么没有理由把它放在那里.默认情况下不要使用返回类型推导.

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天全站免登陆