【问题标题】:How to use the auto and decltype keywords to ease template argument deduction?如何使用 auto 和 decltype 关键字来简化模板参数推导?
【发布时间】:2012-10-23 10:46:50
【问题描述】:

我正在实现合并排序算法。问题是当我尝试在算法中使用自动推导类型的向量时。

template <typename TIterator, typename TCompare>
void mergeSort(TIterator begin, TIterator end, TCompare criterium)
{
     //...
     auto help = *begin;                // help is a value (not a reference)
     QVector<decltype(help)> leftPart;  // now decltype(help) is also a value
     //...                              // and not a reference
}

这行得通。

但是一旦我让算法通过不断的引用传递TIterators,我就会得到一个我这辈子都没有遇到过的错误:

template <typename TIterator, typename TCompare>
void mergeSort(const TIterator& begin, const TIterator& end, TCompare criterium)
{
     //...
     auto help = *begin;                    // help is a value (not a reference)
     QVector<decltype(help)> leftPart;  // now decltype(help) is also a value
     //...
}

结果:

In function 'void mergeSort(const TIterator&, const TIterator&, TCompare)':
internal compiler error: in type_unification_real, at cp/pt.c:14176

我在Ubuntu上使用g++ 4.6.3

出了什么问题?

【问题讨论】:

  • “内部编译器错误”:老实说,这对我来说就像一个编译器错误
  • 在这种情况下你不应该使用const auto&amp;吗?
  • @LyubomirVasilev 实际上我希望 help 是一个值,而不是一个引用,以便能够声明一个与 help 相同类型的 QVector
  • @Jasper:当然。无论输入多么奇怪,都不应该发生内部错误。
  • 不管错误如何,将迭代器作为 const 引用传递是不常见的。按值是正确的。

标签: c++ templates gcc c++11


【解决方案1】:

只要编译器失败,就会发生内部编译器错误,这意味着您发现了一个错误。这就是早期采用新标准通常被称为出血边缘的原因:有时,它会让你流血;)

您的代码可能有问题,也可能没有。仅凭此输出无法判断。可以肯定的是,编译器不支持它,所以您可能想要更改它。

特别是,查找 std::iterator_traits&lt;&gt; 以查看您可以从迭代器的类型中推断出的所有内容:

typename std::iterator_traits<TIterator>::value_type help = *begin;
                                     // ::reference
                                     // ::pointer
                                     // ...

通过绕过自动推导,您可能能够克服编译器错误。


注意:如果您想报告错误,这当然值得称赞,您将被要求生成一个重现该问题的预处理文件。该文件应尽可能小。它可以在 gcc 命令行上使用-E 生成,通常以.ii 扩展名结束。

【讨论】:

  • 谢谢!使用 iterator_traits 代替工作。它编译并通过了单元测试。
  • 您需要帮助吗? QVector::value_type > 有什么问题?
  • @CashCow: a missing typename ;) 否则,不知道,因为我看不到算法的其余部分,所以我不知道之后是否使用了 help
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2011-10-15
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多