Home > Backend Development > C++ > Can `auto` Deduce Private Types in C ?

Can `auto` Deduce Private Types in C ?

Mary-Kate Olsen
Release: 2024-12-19 20:51:12
Original
163 people have browsed it

Can `auto` Deduce Private Types in C  ?

Using 'auto' on Private Types

In C , it may seem counterintuitive that one can utilize 'auto' with private types, as demonstrated in the following code:

1

2

3

4

5

class Foo {

    struct Bar { int i; };

public:

    Bar Baz() { return Bar(); }

};

Copy after login

Normally, it would be expected that attempting to access the private type 'Bar' directly (e.g., Foo::Bar b = f.Baz();) would result in an error. However, this is not the case when using 'auto':

1

2

3

4

5

int main() {

    Foo f;

    auto b = f.Baz();         // ok

    std::cout << b.i;

}

Copy after login

This behavior arises due to the similarity between 'auto' rules and template type deduction. Similar to how private types can be passed to template functions:

1

2

3

4

5

6

7

template <typename T>

void fun(T t) {}

 

int main() {

    Foo f;

    fun(f.Baz());         // ok

}

Copy after login

This ability stems from the fact that while the name of a private type may be inaccessible, the type itself remains usable. Consequently, 'auto' is able to deduce the type correctly and assign it to the 'b' variable, despite being a private type.

The above is the detailed content of Can `auto` Deduce Private Types in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template