Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::declval<T>() work?

Tags:

c++

c++11

I am trying to understand how std::declval<T>() works. I know how to use it, and know what it does, mainly allows you to use decltype without constructing the object, like

decltype(std::declval<Foo>().some_func()) my_type; // no construction of Foo

I know from cppreference.com that std::declval<Foo> "adds" a rvalue reference to Foo, which due to reference collapsing rules ends up being either a rvalue reference or a lvalue reference. My question is why the constructor of Foo is not called? How can one implement a "toy" version of std::declval<T> without constructing the template parameter?

PS: I know it is not the same as the old trick

(*(T*)(nullptr))
like image 916
vsoftco Avatar asked Feb 16 '15 00:02

vsoftco


1 Answers

Basically, in a sizeof or decltype expression you can call functions that aren't implemented anywhere (they need to be declared, not implemented).

E.g.

class Silly { private: Silly( Silly const& ) = delete; };

auto foo() -> Silly&&;

auto main() -> int
{
    sizeof( foo() );
}

The linker should not complain about that.

like image 176
Cheers and hth. - Alf Avatar answered Oct 03 '22 01:10

Cheers and hth. - Alf