Trying to compile this simple class:
#include <vector> struct M { // interface auto begin() -> decltype(identities.begin()) { return identities.begin(); } // implementation private: std::vector<int> identities; };
results in an error:
$ g++-510 where.cpp -std=c++11 where.cpp:57:35: error: ‘struct M’ has no member named ‘identities’ auto begin() ->decltype(this->identities.begin()) ^ where.cpp:57:35: error: ‘struct M’ has no member named ‘identities’ $ clang++ where.cpp -std=c++11 -Wall -pedantic -Wextra where.cpp:57:35: error: no member named 'identities' in 'M' auto begin() ->decltype(this->identities.begin()) ~~~~ ^
Why doesn't decltype
see the class member?
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a template function whose return type depends on the types of its template arguments.
auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.
decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, where you want the type to exactly “track” some expression you're invoking.
Decltype keyword in C++ Decltype stands for declared type of an entity or the type of an expression. It lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. SYNTAX : decltype( expression )
From N3337 [basic.lookup.unqual]/7:
A name used in the definition of a class X outside of a member function body or nested class definition shall be declared in one of the following ways:
- before its use in class X or be a member of a base class of X, or...
Because the trailing return type is part of the function declaration rather than the definition, it can't look ahead to see what else is declared in the class, so you need to declare that member above the function declaration.
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