为什么我可以在私人类型上使用自动? [英] Why can I use auto on a private type?

查看:130
本文介绍了为什么我可以在私人类型上使用自动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以某种方式感到惊讶,下面的代码编译和运行(vc2012& gcc4.7.2)

I was somehow surprised that the following code compiles and runs (vc2012 & gcc4.7.2)

class Foo {
    struct Bar { int i; };
public:
    Bar Baz() { return Bar(); }
};

int main() {
    Foo f;
    // Foo::Bar b = f.Baz();  // error
    auto b = f.Baz();         // ok
    std::cout << b.i;
}

这段代码编译正确吗?为什么是正确的?为什么我可以在私人类型上使用 auto ,而我不能使用它的名字(如预期的)?

Is it correct that this code compiles fine? And why is it correct? Why can I use auto on a private type, while I can't use its name (as expected)?

推荐答案

auto 的规则大部分与模板类型扣除相同。该示例发布的工作原理也是为了同样的原因,你可以将私有类型的对象传递给模板函数:

The rules for auto are, for the most part, the same as for template type deduction. The example posted works for the same reason you can pass objects of private types to template functions:

template <typename T>
void fun(T t) {}

int main() {
    Foo f;
    fun(f.Baz());         // ok
}

为什么我们可以将私有类型的对象传递给模板函数,你问?因为只有类型的名称是不可访问的。类型本身仍然可用,这就是为什么你可以将其返回到客户端代码。

And why can we pass objects of private types to template functions, you ask? Because only the name of the type is inaccessible. The type itself is still usable, which why you can return it to client code at all.

这篇关于为什么我可以在私人类型上使用自动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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