处理模板方法中的错误
Handling an error in a template method
我在寻找处理此模板函数中的错误的良好解决方案时遇到问题。
template<typename K, typename V>
const V& DirectHashmap<K, V>::lookup(K key) const
{
int pos = position(key);
return _values.get(pos)->value;
}
我无法 return 错误代码,因为我不知道我正在 return 的类型。我更喜欢不使用异常,因为我们以前在项目中从未使用过异常,如果这是唯一有异常的方法,它会不一致。
如果有人有好的解决方案请告诉我!非常感谢所有反馈。
您应该 return 一个 const_iterator
到您的 collection。
最终用户可以测试它是否等同于您的 collection 的 .end()
。这就是 STL 中容器的典型工作方式。 (参考map::find, unordered_map::find, and unordered_set::find)
从 C++14 开始,我们现在有了模板变量,您可以使用它让客户端代码为示例代码中的类型定义错误。在实践中,我不会将它们设为全局变量,而是让客户端可以打开模板函数知道的一些命名空间。
#include <iostream>
template<typename T>
T error;
template<>
int error<int> = -1;
int main(int argc, char* argv[])
{
std::cout << error<int> << std::endl;
return 0;
}
我在寻找处理此模板函数中的错误的良好解决方案时遇到问题。
template<typename K, typename V>
const V& DirectHashmap<K, V>::lookup(K key) const
{
int pos = position(key);
return _values.get(pos)->value;
}
我无法 return 错误代码,因为我不知道我正在 return 的类型。我更喜欢不使用异常,因为我们以前在项目中从未使用过异常,如果这是唯一有异常的方法,它会不一致。
如果有人有好的解决方案请告诉我!非常感谢所有反馈。
您应该 return 一个 const_iterator
到您的 collection。
最终用户可以测试它是否等同于您的 collection 的 .end()
。这就是 STL 中容器的典型工作方式。 (参考map::find, unordered_map::find, and unordered_set::find)
从 C++14 开始,我们现在有了模板变量,您可以使用它让客户端代码为示例代码中的类型定义错误。在实践中,我不会将它们设为全局变量,而是让客户端可以打开模板函数知道的一些命名空间。
#include <iostream>
template<typename T>
T error;
template<>
int error<int> = -1;
int main(int argc, char* argv[])
{
std::cout << error<int> << std::endl;
return 0;
}