考虑一个实现容器的类模板,其中包含用于选择其存储位置的选项。
template<class T>
class Container {
public:
enum StorageOption {A,B};
Container(StorageOption opt_): option(opt_) {}
private:
StorageOption option;
};
此处 StorageOption
被选为成员,因为它仅在类中使用。
现在,要实例化类,我需要重复模板参数,例如:
{
Container<int> c( Container<int>::A );
}
有没有一种方法可以避免重复参数,同时让 StorageOption
成为成员,或者有没有更好的方法来实现该选项?
最佳答案
通常通过在基类中定义它来实现。
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 );
关于c++ - 避免在类模板中重复访问枚举的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15160557/