首页 > 解决方案 > 使用 C++ 模板切换算法

问题描述

我有一个具有pointQuery函数的 C++ 类。目前,当我必须在线性搜索和二进制搜索之间切换时,我会注释代码的另一部分。我看到了这篇文章,并试图重构我的代码。我的代码如下:

namespace searchStrategy{
    struct linearSearch{};    
    struct binarySearch{};
}

template<typename T, typename LookupStrategy> class leaf:public rtNode<T>{
    public:T points[maxCapLeaf][d]; // search to be done on this array
    // some other class members, most of which used in the search

    template<typename searchStrategy::linearSearch> bool pointQuery(const T* f) const{
        // some code
    }

    template<typename searchStrategy::binarySearch> bool pointQuery(const T* f) const{
        // some code
    }

};

类的对象被创建为:

leaf<T, LookupStrategy>* temp = new leaf<T, LookupStrategy>(some_input_params);

LookupStrategy在哪里。searchStrategy::binarySearchsearchStrategy::linearSearch

当我编译它时,我收到以下错误:

/file_address/template.cpp:164:39: error: non-type template parameters of class type only available with ‘-std=c++2a’ or ‘-std=gnu++2a’
  164 |     template<typename searchStrategy::linearSearch> bool pointQuery(const T* f) const{
      |                                       ^~~~~~~~~~~~
/file_address/template.cpp:200:39: error: non-type template parameters of class type only available with ‘-std=c++2a’ or ‘-std=gnu++2a’
  200 |     template<typename searchStrategy::binarySearch> bool pointQuery(const T* f) const{
      |                                       ^~~~~~~~~~~~
/file_address/template.cpp:200:58: error: ‘template<class T, class LookupStrategy> template<<typeprefixerror><anonymous> > bool leaf<T, LookupStrategy>::pointQuery(const T*) const’ cannot be overloaded with ‘template<class T, class LookupStrategy> template<<typeprefixerror><anonymous> > bool leaf<T, LookupStrategy>::pointQuery(const T*) const’
  200 |     template<typename searchStrategy::binarySearch> bool pointQuery(const T* f) const{
      |                                                          ^~~~~~~~~~
/file_address/template.cpp:164:58: note: previous declaration ‘template<class T, class LookupStrategy> template<<typeprefixerror><anonymous> > bool leaf<T, LookupStrategy>::pointQuery(const T*) const’
  164 |     template<typename searchStrategy::linearSearch> bool pointQuery(const T* f) const{
      |

有人可以解释我做错了什么,我该如何解决这个问题?(请注意,函数需要保留在类本身中,我无法将其转移到命名空间,因为搜索函数中使用了很多类成员)谢谢...

标签: c++classtemplates

解决方案


namespace searchStrategy {
    struct linearSearch{};    
    struct binarySearch{};
}

template<typename T, typename LookupStrategy> class leaf: public rtNode<T> {
  private:
    // Overload 1
    bool pointQuery(const T* f, linearSearch) const {
        // some code
    }

    // Overload 2
    bool pointQuery(const T* f, binarySearch) const {
        // some code
    }

  public:
    T points[maxCapLeaf][d];

    bool pointQuery(const T* f) const {
        return pointQuery(points, LookupStrategy{});
    }
};

推荐阅读