我有以下模板函数:
template<typename K, typename V>
bool hasKey( const std::map<K, V>& m, K& k ) {
return m.find(k) != m.end();
}
映射中的键不是const
。
现在,我可能有一个const K
。我如何编写一个模板,允许我将 K 和
const K` 传递给函数?
每次调用函数时都使用const_cast
的解决方案吗?
最佳答案
你可以通过以下方式实现你想要的
template <typename Key, typename Value, typename K>
bool hasKey(const std::map<Key, Value>& mp, const K& k) {
return mp.find(k) != mp.end();
}
通过这种方式,您可以确定在查看函数声明时不会修改任何操作数,因为它们都是对 const
的引用。
键类型的非 const 和 const 引用(甚至右值)都可以传递给 std::map
中的 .find()
方法。这是有效的,因为 .find()
方法通过 const 引用接受键类型,所以如果你传递一个非常量引用,它无论如何都会被 const 引用绑定(bind),所以它没有什么区别.
通过单独模板化键类型获得的另一件事是与透明比较器的兼容性(C++14 起,参见 http://en.cppreference.com/w/cpp/container/map/find )。有关透明比较器的更多信息,请参阅 What are transparent comparators? .
关于c++ - 如何忽略函数模板中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44878265/