Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用于逻辑拆分的非类型模板_C++_Templates_Design Patterns - Fatal编程技术网

C++ 用于逻辑拆分的非类型模板

C++ 用于逻辑拆分的非类型模板,c++,templates,design-patterns,C++,Templates,Design Patterns,我有以下情况,我不知道我的方法是否正确。我正在从事一个具有以下结构的项目: class Filesystem { public: Filesystem(Profile* profile); OpenFile(const std::string& file,OpenFileCallback); ReadFile(int file_handle,Buffer* buffer,ulong offset,ulong length); protected:

我有以下情况,我不知道我的方法是否正确。我正在从事一个具有以下结构的项目:

class Filesystem {
public:
      Filesystem(Profile* profile);
      OpenFile(const std::string& file,OpenFileCallback);
      ReadFile(int file_handle,Buffer* buffer,ulong offset,ulong length);
protected:
    DiskRouter* disk_router_;
...
}

// --- implementation ---
Filesystem::Filesystem(Profile* profile) 
    :disk_router_(Disk_Router::Get(profile)){
}
此类使用操作抽象来运行OpenFile操作、ReadFile操作等。这些操作被发送到负责相关文件系统类型的路由器

class Operation {
public:
    Operation(Disk_Router* router) {
    }
}
我想使用一个非类型参数来选择目标路由器,并使用一个目标策略在路由器之间进行选择。基本上,代码是可重用的,我不想改变一个好的实现,也不想改变某些东西,使其适用于所有逻辑。 比如:

template <int DESTINATION>
class Filesystem{
 ...
protected:
  Destination_Policy<DESTINATION>::DestinationType router_type;
}
// ----- implementation
template <int DESTINATION>
Filesystem<DESTINATION>::Filesystem(Profile* profile)
      :disk_router_(Destination_Policy<DESTINATION>::Get(profile)) {
}
模板
类文件系统{
...
受保护的:
目的地\策略::目的地类型路由器\类型;
}
//----实施
模板
文件系统::文件系统(概要文件*概要文件)
:磁盘\路由器\目标\策略::获取(配置文件)){
}
行动将变成:

template <class Destination>
class Operation{..}
模板
类操作{..}
我正在努力实现的目标:

  • 我不需要描述路由器的通用接口。它们可以独立变化

  • 如果需要,我可以基于非类型专门化某些方法

这个逻辑正确吗?
谢谢大家!

我想到了两件事,但由于您的问题只显示了代码的一小部分,只有您可以判断它们是否适用:

第一件事是,
int
没有任何真正的意义。我假设可能值的数量及其含义应该限制在一个特定的集合中,因此使用
enum
(或者更好地使用
enum类,如果C++11可用)似乎更合适。您仍然可以像使用
int
一样进行专门化,只是您的代码将变得更可读,更不容易出错

但是第二件事和真正的问题是,为什么需要非类型参数?看起来您可以直接传递策略类型:

template <typename DestinationPolicy>
class Filesystem{
 ...
protected:
  typename DestinationPolicy::DestinationType disk_router_;
}
// ----- implementation
template <typename DestinationPolicy>
Filesystem<DestinationPolicy>::Filesystem(Profile* profile)
      :disk_router_(DestinationPolicy::Get(profile)) {
}
模板
类文件系统{
...
受保护的:
typename DestinationPolicy::DestinationType磁盘\u路由器;
}
//----实施
模板
文件系统::文件系统(概要文件*概要文件)
:磁盘\路由器\目标策略::获取(配置文件)){
}
等等


如果您的大多数策略最终看起来几乎相同,请为它们创建一个基类,只覆盖真正策略所需的内容。与基于
enum
的解决方案相比,它还使您更加灵活,因为您可以在以后添加任意数量的策略,并为每个策略指定一个描述性名称。

是的,我使用的是enum,但直接使用目标策略更有意义。我仍在分析是否有一个符合接口的DiskRouter适配器不适用。但这意味着更多的代码更改和一些接口限制,我对此感到不舒服。