避免重复模板参数来访问类模板中的枚举

rit*_*ter 5 c++ enums templates

考虑一个实现容器的类模板,该容器包含用于选择其存储位置的选项.

template<class T>
class Container {
public:
  enum StorageOption {A,B};
  Container(StorageOption opt_): option(opt_) {}
private:
  StorageOption option;
};
Run Code Online (Sandbox Code Playgroud)

这里StorageOption被选为成员,因为它只在课堂上使用.

现在,要实例化该类,我需要重复模板参数,如:

{
  Container<int> c( Container<int>::A );
}
Run Code Online (Sandbox Code Playgroud)

有没有办法避免重复参数,同时StorageOption成为一个成员或有更好的方法来实现该选项?

小智 7

通常通过在基类中定义它来实现.

class ContainerBase {
public:
  enum StorageOption {A,B};
};


template<class T>
class Container : public ContainerBase{
public:
  Container(StorageOption opt_): option(opt_) {}
private:
  StorageOption option;
};

Container<int> c( ContainerBase::A );
Run Code Online (Sandbox Code Playgroud)