简体   繁体   中英

Return NULL when using template in C++

If I have an interface as below:

template <typename V, typename K>
V get(K key);  // Return the value of the key 

Does the specification "return NULL when the key is not found" make sense? Is there anyway to handle the case when the key is not found except throwing an exception?

Also is throwing an exception the best way here to handle non-existing key?

You cannot assume that V is a pointer. If V is int , for example, you cannot return the nullptr as it is no valid value for an int . And if V is a pointer type, think whether the nullptr would be a valid value for it to be inserted into your map. If so, how could the caller distinguish the nullptr that is return ed to mean “not found” from the “actual” nullptr ?

If you are okay return ing a pointer to the item in the map, rather than a copy, consider this signature.

template <typename V, typename K>
V * get(K key);

Use const V * if you'd rather not have the caller modify the object in the map.

Alternatively, you could use an optional<T> . You can find an implementation in Boost as well as as an experimental extension to the standard library .

Of course, you can also throw an exception to indicate that the key is not present in your map. However, this would only be considered good style by most coding standards if your clients had a reasonable way to know ahead of time whether the key is present or not. Exceptions should be used to signal abnormal, erroneous conditions. The fact that a key is not present in a map is unlikely to qualify for this, unless in your situation, the set of keys can be assumed to be known.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM