Narek
Narek

Reputation: 39871

How does decltype work?

Is it evaluated only on compile time? Does it look what is the expression type or it's return type and just substitutes it? I.e. does it work as macros preprocessor substitutions? Also if I wrote this:

std::map<std::string, int> m;
decltype(m.cbegin()) i;

Is it going to call actually the cbegin and I will pay for some performance here?

EDIT: I know already that I can write decltype(m)::const_iterator i;

Upvotes: 6

Views: 1284

Answers (2)

Victor Dyachenko
Victor Dyachenko

Reputation: 1401

I cannot write decltype(m)::const_iterator i;

You can!

std::map<std::string, int> m;
decltype(m)::const_iterator i; // same as std::map<std::string, int>::const_iterator

GNU C++ compiles this snippet well.

Upvotes: 1

Ami Tavory
Ami Tavory

Reputation: 76297

decltype strictly works in compile time. As such, you can use it with code that would dereference end iterators, or use

decltype(sqrt(-1.))

There is absolutely no runtime penalty associated with this - it simply doesn't get executed.


Incidentally, regarding your comment:

You should use decltype with an expression that returns some value. Somewhat Ironically, decltype(m)::const_iterator i; is not an expression that returns a value - it is a definition of a value.

Upvotes: 5

Related Questions