c++ - 使用 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::binarySearch
searchStrategy::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{
|
有人可以解释我做错了什么,我该如何解决这个问题?(请注意,函数需要保留在类本身中,我无法将其转移到命名空间,因为搜索函数中使用了很多类成员)谢谢...
解决方案
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{});
}
};
推荐阅读
- matlab - 从图中的轴获取当前选定的数据点
- mysql - 显示匹配字段外键和主键
- java - 如何在 Spring Boot 或 Java 中将 json 响应列表合并到另一个列表中?
- angular - 处理来自函数和 fixture.detectChanges() 的变量更改
- sql - 如何在 SQL Server 中检查所有列都为 0 而不用 OR 条件指定所有列?
- python - matplotlib 显示不完整的刻度标签
- excel - Excel VBA自定义函数重新计算不起作用
- javascript - 禁用提交按钮,直到验证所有表单字段
- python - 使用 OpenCV SIFT 和 DescriptorMatcher 的图像之间的错误匹配过多
- swift - 如果文本包含表情符号,则范围从 swift 为 nil