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))
declval
– Callaghantemplate< class T > typename std::add_rvalue_reference<T>::type declval();
is literally all you need. Live example – Sickly.
operator to select a function from a rvalue reference to an object without constructing the object, likestd::declval<Foo>().f()
I know thatstd::declval<Foo>()
is of typeFoo&&
, but didn't know you can "access" it's member function via the.
operator, as you didn't construct the object. I thought one should have use the scope operator::
– Callaghanprintf("%p\n", (void*)(&((struct s *)NULL)->i));
in some real code. and for me,std::declval<Foo>().f()
is a similar usage: extract meta information other than calling the function/access the variable – Willenewillet