Created
May 20, 2014 02:43
-
-
Save kasajian/1d96b3b22e3523fb1ab1 to your computer and use it in GitHub Desktop.
C++ template to force use of function return value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If it is important that a return value not be ignored by the caller of a function, | |
// the template dont_ignore may be used as follows: | |
// BEFORE: | |
// int add( int x, int y ) | |
// { | |
// return x + y; | |
// } | |
// AFTER: | |
// dont_ignore<int> add( int x, int y ) | |
// { | |
// return x + y; | |
// } | |
// | |
// When the caller of the function does not use the return value, | |
// an exception is thrown. Definition of dont_ignore: | |
template<class T> | |
struct dont_ignore | |
{ | |
const T v; | |
bool used; | |
dont_ignore( const T& v ) | |
: v( v ), used( false ) | |
{} | |
~dont_ignore() | |
{ | |
if ( !used ) | |
throw std::runtime_error( "return value not used" ); | |
} | |
operator T() | |
{ | |
used = true; | |
return v; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment