0

我在我编写的模板稀疏矩阵类上有一个 STL 风格的迭代器,YaleStorage<D>. 我operator==为矩阵类编写了一个允许比较两个D可能不同的矩阵。

我的迭代器也是模板——所以我可以拥有const_iteratoriterator作为 的特化iterator_T<RefType>,其中RefType可能是const D&D&

即使D不同,我也需要这些迭代器具有可比性。我并不特别需要 constness 来区分(const_iterator不需要将 a 与 a 进行比较iterator)。这是我写的operator!=等等:

template <typename D>
class YaleStorage {
  template <typename RefType>
  class iterator_T {
    template <typename E, typename ERefType = typename enable_if_else<std::is_const<RefType>::value, const E&, E&>::type>
    bool operator!=(const typename YaleStorage<E>::template stored_diagonal_iterator_T<ERefType>& rhs) const { /* some comparison code */ }
  };
  typedef iterator_T<D&>       iterator;
  typedef iterator_T<const D&> const_iterator;

  const_iterator cbegin() const { /* returns a const_iterator */ }
  const_iterator cend() const { /* returns the end const_iterator */ }
};

请注意,我自己编写了enable_if_else,因为我在 STL 中找不到类似的函数。这是:

template <bool B, typename TA, typename TB>
struct enable_if_else {};
template <typename TA, typename TB>
struct enable_if_else<true, TA, TB> {  typedef TA type; };
template <typename TA, typename TB>
struct enable_if_else<false, TA, TB> { typedef TB type; };

不幸的是,当我尝试进行常规迭代器比较( where D=E)时,我得到了一大堆错误,例如:

compiling ../../../../ext/nmatrix/storage/yale.cpp
../../../../ext/nmatrix/storage/yale.cpp: In instantiation of ‘VALUE nm::yale_storage::each_stored_with_indices(VALUE) [with DType = unsigned char; VALUE = long unsigned int]’:
../../../../ext/nmatrix/storage/yale.cpp:1686:3:   required from here
../../../../ext/nmatrix/storage/yale.cpp:1567:83: error: no match for ‘operator!=’ in ‘d != nm::YaleStorage<D>::cend() const [with D = unsigned char; nm::YaleStorage<D>::const_iterator = nm::YaleStorage<unsigned char>::iterator_T<const unsigned char&>]()’
../../../../ext/nmatrix/storage/yale.cpp:1567:83: note: candidates are:
In file included from ../../../../ext/nmatrix/storage/yale.cpp:64:0:
../../../../ext/nmatrix/storage/yale.h:438:10: note: template<class E, class ERefType> bool nm::YaleStorage<D>::iterator_T::operator!=(const typename nm::YaleStorage<E>::iterator_T<ERefType>&) const [with E = E; ERefType = ERefType; RefType = const unsigned char&; D = unsigned char]
../../../../ext/nmatrix/storage/yale.h:438:10: note:   template argument deduction/substitution failed:
../../../../ext/nmatrix/storage/yale.cpp:1567:83: note:   couldn't deduce template parameter ‘E’

我已经尝试过明确地转换结果,cend()所以它知道比较的两边是什么,但我不明白为什么它会因此而窒息。

template <typename DType>
static VALUE each_with_indices(VALUE nm) {
  YaleStorage<DType> y(s);

  // The next line is 1567:
  for (typename YaleStorage<DType>::const_iterator d = y.cbegin(); d != y.cend()); ++d) {
    /* Do some stuff with d */
  }
}

我知道如何为非operator函数显式指定模板参数,但如何为运算符指定模板参数?还有另一种更好的方法吗?在我看来,编译器应该很清楚E这里有什么。

4

0 回答 0