Name
Name

Reputation: 156

Calling or not to abs() function, depending on template type being unsigned, if it is possible?

trying to compile code:

template<typename K, typename V>
typename ConcurrentMap<K, V>::Access ConcurrentMap<K, V>::operator[](const K &key) {
//    auto ind = abs(static_cast<long long>(key)) % bucket_count;
    auto ind = abs(key) % bucket_count;
    return {lock_guard<mutex>(mutexes[ind]), sub_maps[ind][key]};
}

and getting an error:

error: call of overloaded 'abs(const long long unsigned int&)' is ambiguous

Error is caused because of template parameter K being unsigned. Therefore, abs() cannot be called on it.

Can I disable calling to abs(), in case when template parameter K is unsigned?

Or please suggest some best-practice solution for such cases. Thanks!

Upvotes: 0

Views: 125

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38539

#include <type_traits>

template<typename K, typename V>
typename ConcurrentMap<K, V>::Access ConcurrentMap<K, V>::operator[](const K &key) {
  K ind;
  if constexpr (std::is_unsigned<K>::value)
    ind = key % bucket_count;
  else
    ind = abs(key) % bucket_count;
  return {lock_guard<mutex>(mutexes[ind]), sub_maps[ind][key]};
}

Upvotes: 5

Related Questions