Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c++ - Why does std::declval add a reference?

std::declval is a compile-time utility used to construct an expression for the purpose of determining its type. It is defined like this:

template< class T >
typename std::add_rvalue_reference<T>::type declval() noexcept;

Would this not be simpler instead?

template< class T >
T declval() noexcept;

What is the advantage of a reference return type? And shouldn't it be called declref?

The earliest historical example I find is n2958, which calls the function value() but already always returns a reference.

Note, the operand of decltype does not need to have an accessible destructor, i.e. it is not semantically checked as a full-expression.

template< typename t >
t declprval() noexcept;

class c { ~ c (); };
decltype ( declprval< c >() ) * p = nullptr; // OK
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The "no temporary is introduced for function returning prvalue of object type in decltype" rule applies only if the function call itself is either the operand of decltype or the right operand of a comma operator that's the operand of decltype (§5.2.2 [expr.call]/p11), which means that given declprval in the OP,

template< typename t >
t declprval() noexcept;

class c { ~ c (); };

int f(c &&);

decltype(f(declprval<c>())) i;  // error: inaccessible destructor

doesn't compile. More generally, returning T would prevent most non-trivial uses of declval with incomplete types, type with private destructors, and the like:

class D;

int f(D &&);

decltype(f(declprval<D>())) i2;  // doesn't compile. D must be a complete type

and doing so has little benefit since xvalues are pretty much indistinguishable from prvalues except when you use decltype on them, and you don't usually use decltype directly on the return value of declval - you know the type already.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...