Skip to content

Instantly share code, notes, and snippets.

@kasajian
Created May 20, 2014 02:43
Show Gist options
  • Save kasajian/1d96b3b22e3523fb1ab1 to your computer and use it in GitHub Desktop.
Save kasajian/1d96b3b22e3523fb1ab1 to your computer and use it in GitHub Desktop.
C++ template to force use of function return value.
// 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