jeudi 26 février 2015

disallow passing of rvalue reference to a function

We have the following convenience function that fetches a value from a map or returns a fallback default value if key not found.



template <class Collection> const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return value;
}
return it->second;
}


The problem with this function that it easily allow bugs when passing temporary objects. For example:



const string& foo = FindWithDefault(my_map, "");


Is it possible to disallow passing rvalue references to the third argument in some way by using std::is_rvalue_reference and static assert?


Aucun commentaire:

Enregistrer un commentaire