1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
#include <string>
#include <limits>
#include <type_traits>
namespace utility
{
template < typename T > T& get_value( T& value, const std::string& prompt = "?" )
{
std::cout << prompt << ' ' ;
if( std::cin >> value ) return value ;
std::cerr << "bad input.\n" ;
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return get_value( value, prompt ) ;
}
template < typename T > T get_value( const std::string& prompt = "?" )
{
static_assert( std::is_default_constructible<T>::value, "not DefaultConstructible" ) ;
static_assert( std::is_constructible<T,T&&>::value, "not copyable or moveable" ) ;
T value ;
get_value( value, prompt ) ;
return value ;
}
template < typename T, typename FN >
T& get_value( T& value, FN is_valid, const std::string& prompt = "?" )
{
get_value( value, prompt ) ;
if( is_valid(value) ) return value ;
std::cerr << "invalid value\n" ;
return get_value( value, is_valid, prompt ) ;
}
template < typename T, typename FN >
T get_value( FN is_valid, const std::string& prompt = "?" )
{
static_assert( std::is_default_constructible<T>::value, "not DefaultConstructible" ) ;
static_assert( std::is_constructible<T,T&&>::value, "not copyable or moveable" ) ;
T value ;
get_value<T>( value, is_valid, prompt ) ;
return value ;
}
}
int main()
{
const int v = utility::get_value<int>( []( int v ) { return v%2 == 1 ; }, "enter an odd integer:" ) ;
std::cout << v << '\n' ;
}
|