Temporary Variables: Runtime rvalue Detection - The RVALUE_TEST macro
(Page 3 of 4 )
Niebler has found a smart way to use the characteristics of the ternary operator to determine whether something is an rvalue or not. First let's have a look at the macro:
#define RVALUE_TEST( container ) \
try { ( true ? rvalue_probe() : (container) ); } \
catch ( char const *result ) { cout << result << ‘\n’; }
It probably looks a bit peculiar because the conditional expression is missing; instead the condition has already been evaluated to true. The trick here is that the ternary operator is not used in its regular way, but to test whether container is an rvalue or not.
So what kind of object is the rvalue_probe?
struct rvalue_probe {
template < class R > operator R () { throw “rvalue”; }
template < class L > operator L&() const { throw “lvalue”; }
}
This code makes it possible to print "rvalue" to stdout when evaluating RVALUE_TEST(“test”) and "lvalue" to stdout when evaluating RVALUE_TEST(cout); ! To understand how the ternary operator evaluates the expression in the macro we need to take a closer look at its definition in the C++ Standard.
Next: Determining Type >>
More C++ Articles
More By J. Nakamura