Home arrow C++ arrow Page 3 - Temporary Variables: Runtime rvalue Detection
C++

Temporary Variables: Runtime rvalue Detection


In this final article in the series covering temporary variables, Jun Nakamura explains how you can test whether a variable is temporary or not, by using the ternary conditional operator.

Author Info:
By: J. Nakamura
Rating: 4 stars4 stars4 stars4 stars4 stars / 6
October 17, 2005
TABLE OF CONTENTS:
  1. · Temporary Variables: Runtime rvalue Detection
  2. · The Ternary Conditional Operator
  3. · The RVALUE_TEST macro
  4. · Determining Type

print this article
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials