Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decltype not see the member declaration? [duplicate]

Tags:

c++

c++11

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?

like image 762
Bulletmagnet Avatar asked Jul 03 '15 09:07

Bulletmagnet


People also ask

What does decltype do in c++?

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.

What is the difference between auto and decltype Auto?

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.

What does decltype auto do?

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.

What does decltype stand for?

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 )


1 Answers

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.

like image 76
TartanLlama Avatar answered Sep 20 '22 10:09

TartanLlama