9
9
#include < limits>
10
10
#include < list>
11
11
#include < map>
12
+ #include < optional>
12
13
#include < set>
13
14
#include < string>
14
15
#include < string_view>
@@ -1839,20 +1840,21 @@ class weighted_string_id_reader : public generic_typed_reader<weighted_string_id
1839
1840
public:
1840
1841
static constexpr bool read_objects = true ;
1841
1842
1842
- V default_weight;
1843
- explicit weighted_string_id_reader ( V default_weight ) : default_weight( default_weight ) {};
1843
+ std::optional<V> default_weight;
1844
+ explicit weighted_string_id_reader ( std::optional<V> default_weight ) : default_weight(
1845
+ default_weight ) {};
1844
1846
1845
1847
std::pair<K, V> get_next ( const JsonValue &val ) const {
1846
1848
if ( val.is_member () ) {
1847
1849
const JsonMember &jm = dynamic_cast <const JsonMember &>( val );
1848
1850
return std::pair<K, V>( jm.name (), static_cast <V>( val.get_float () ) );
1849
1851
} else if ( val.test_object () ) {
1850
1852
JsonObject inline_pair = val.get_object ();
1851
- if ( !( inline_pair.size () == 1 || inline_pair.size () == 2 ) ) {
1853
+ if ( !( ( inline_pair.size () == 1 && default_weight. has_value () ) || inline_pair.size () == 2 ) ) {
1852
1854
inline_pair.throw_error ( " weighted_string_id_reader failed to read object" );
1853
1855
}
1854
1856
K pair_key;
1855
- V pair_val = default_weight;
1857
+ V pair_val = default_weight. value_or ( V () ) ;
1856
1858
for ( JsonMember mem : inline_pair ) {
1857
1859
if ( mem.test_string () ) {
1858
1860
pair_key = K ( std::move ( mem.get_string () ) );
@@ -1871,12 +1873,14 @@ class weighted_string_id_reader : public generic_typed_reader<weighted_string_id
1871
1873
return std::pair<K, V>(
1872
1874
K ( std::move ( arr[0 ].get_string () ) ),
1873
1875
static_cast <V>( arr[1 ].get_float () ) );
1874
- } else {
1876
+ } else if ( default_weight. has_value () ) {
1875
1877
if ( val.test_string () ) {
1876
1878
return std::pair<K, V>(
1877
- K ( std::move ( val.get_string () ) ), default_weight );
1879
+ K ( std::move ( val.get_string () ) ), * default_weight );
1878
1880
}
1879
1881
val.throw_error ( " weighted_string_id_reader provided with invalid string_id" );
1882
+ } else {
1883
+ val.throw_error ( " weighted_string_id_reader requires two entries" );
1880
1884
}
1881
1885
}
1882
1886
};
0 commit comments