In this code:
struct
{
auto operator[](const char*)
{
return *this;
}
} m_some_class;
What is type of auto
in here?
In C++14, you can just use auto as a return type.
In computer programming, the return type (or result type) defines and constrains the data type of the value returned from a subroutine or method. In many programming languages (especially statically-typed programming languages such as C, C++, Java) the return type must be explicitly specified when declaring a function.
C++: “auto” return type deduction The “auto” keyword used to say the compiler: “The return type of this function is declared at the end”. In C++14, the compiler deduces the return type of the methods that have “auto” as return type.
What is type of
auto
in here ?
The type is decltype(m_some_class)
- I.e., the return value is of the same type as the variable m_some_class
.
Note that the function will return a copy of *this
.
If a reference to *this
is wanted instead, you can use
auto&
or, since C++14, the more generic decltype(auto)
.
For anonymous structure types, internally the compiler creates a name and the auto in your case return the structure.
You can see below, that your anonymous structure is given name __anon_1_1
and the operator[]
function returns object of __anon_1_1
structure. m_some_class
is instance of type __anon_1_1
cppinsights website provides a way to understand
your code
struct
{
auto operator[](const char*)
{
return *this;
}
}m_some_class;
compiler version
struct __anon_1_1
{
inline __anon_1_1 operator[](const char *)
{
return __anon_1_1(*this);
}
// inline constexpr __anon_1_1() noexcept = default;
// inline constexpr __anon_1_1(const __anon_1_1 &) noexcept = default;
};
__anon_1_1 m_some_class = __anon_1_1();
The line in the given code:
return *this;
returns the struct m_some_class
itself, i.e. the type of the operator[]
is:
decltype(m_some_class); // i.e. the type returned is the same as the struct
Also, notice that this will only return a copy instance of the struct since the passed argument isn't given any reference-to operator. Any changes made to the copy of the struct won't affect the original struct.
auto
keyword?The auto
keyword is typically used in those situations when the type of something is not known to the programmer or it's too lengthy to type either.
Also, the type defined by auto
may vary dependent upon the various situations. For instance:
auto len = vector.size(); // len is now defined as size_t in compile time
In some systems, the type of len
maybe unsigned long
and in my case, it's unsigned long long
, here you can't explicitly define which qualifier to use correctly in this indeterminate place. Here we use auto
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With