CPP templated member function specialization

本小妞迷上赌 提交于 2019-12-10 19:42:22

问题


I'm trying to specialize the member function moment() only (not the hole class) like this:

template<class Derived, class T>
class AbstractWavelet {
public:
  [...]

  template<bool useCache>
  const typename T::scalar moment(const int i, const int j) const {
    return abstractWaveletSpecialization<Derived, T, useCache>::moment(static_cast<const Derived*>(this), i, j);
  }
  template<bool useCache>
  friend const typename T::scalar abstractWaveletSpecialization<Derived, T, useCache>::moment(const Derived* const that, const int i, const int j);

protected:
  // returns the jth moment of the ith scaling function
  template<bool useCache>
  inline const typename T::scalar momentImpl(const int j, const int i) const {
    [...]
  } // momentImpl
};

The actual specialization happens in an extra abstractWaveletSpecialization struct:

template<class Derived, class T, bool useCache>
struct abstractWaveletSpecialization {
  inline static const typename T::scalar moment(const Derived* const that, const int i, const int j) {
    return that->momentImpl<useCache>(i,j);
  }
};


template<class Derived, class T> 
struct abstractWaveletSpecialization<Derived, T, true> {

  typedef const std::pair<const int, const int> momentCacheKey;
  typedef std::map<momentCacheKey,
               const typename T::scalar> momentCacheType;
  static momentCacheType momentCache;


  inline static const typename T::scalar moment(const Derived* const that, const int i, const int j) {
    momentCacheKey cacheKey(i,j);
    typename momentCacheType::iterator idx = momentCache.find(cacheKey);

    if (idx == momentCache.end())
      return that->momentImpl<true>(i, j);  // COMPILE ERROR HERE
    else
      return momentCache[cacheKey];
  }
};

The problem is that I cannot call momentImpl() in the specialized abstractWaveletSpecialization struct:

error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘bool’ to binary ‘operator<’

But the compiler does not complain about the call of momentImpl in the non-specialized abstractWaveletSpecialization struct.

Is my approach forbidden in C++? Or is there any way to make this work?


回答1:


Can you try that->template momentImpl<true>(i, j); please ? It's a way to tell the compiler "Hey, the thing after -> is a templated call"



来源:https://stackoverflow.com/questions/3333567/cpp-templated-member-function-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!