【问题标题】:Handling an error in a template method处理模板方法中的错误
【发布时间】:2017-08-21 15:20:08
【问题描述】:

我无法找到一个好的解决方案来处理此模板函数中的错误。

template<typename K, typename V>
const V& DirectHashmap<K, V>::lookup(K key) const
{
    int pos = position(key);

    return _values.get(pos)->value;
}

我无法返回错误代码,因为我不知道要返回的类型。我不喜欢使用异常,因为我们之前从未在项目中使用过异常,如果这是唯一有异常的方法,那将是不一致的。

如果有人有好的解决方案,请告诉我!非常感谢所有反馈。

【问题讨论】:

  • std::pair&lt;bool, V&amp;&gt;?
  • 返回optional&lt;V&amp;&gt;?
  • 可能是返回bool isFound,并通过引用接受第二个参数V&,并用找到的对象更新它?

标签: c++ templates error-handling return return-value


【解决方案1】:

从 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;
}

【讨论】:

    【解决方案2】:

    您应该将 const_iterator 返回到您的收藏中。

    最终用户可以测试它是否等同于您的收藏集的.end()。这就是 STL 中的容器通常的工作方式。 (参考map::findunordered_map::findunordered_set::find

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-13
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多