C ++-使用没有模板参数的模板类中的枚举 [英] C++ - Use enum from template class without template parameter

查看:69
本文介绍了C ++-使用没有模板参数的模板类中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template<typename T> class SomeClass{

public:
    enum SomeEnum{ SOME_FLAG};

};

SomeClass::SomeEnum some_enum =      SomeClass::SomeEnum::SOME_FLAG;       //NO
SomeClass<int>::SomeEnum some_enum = SomeClass::SomeEnum::SOME_FLAG;       //NO
SomeClass<int>::SomeEnum some_enum = SomeClass<int>::SomeEnum::SOME_FLAG;  //YES

这不会编译,因为


类SomeClass,没有模板参数使用

class SomeClass used without template parameters

没有模板,没有办法/解决方法来使用它参数,还可以为该类创建该枚举 global ,因此它不依赖于该参数。

Is there no way / workaround to use it without template parameter, kinda make that enum global for that class, so it doesn't depend on the parameter.

这不是我不能键入它们,但它们可能又长又复杂,代码将更难阅读,在这里我不能使用诸如auto之类的东西。
(我是模板的新手,如果这个问题很la脚,对不起。)

It's not that I can't type them but they can be long and complicated, the code will be harder to read and I can't use something like auto here. (I'm new to templates so sorry if this question is lame.)

推荐答案

如果要附上您在原因的类定义中的枚举(我不能说真正的问题是什么),您仍然可以引入一个不是类模板并且包含枚举的其他类,然后使用您的继承类模板。就是这样。

例如:

If you want to enclose your enum in a class definition for reasons (I cannot say what's the real problem), you can still introduce one more class that isn't a class template and contains the enum, then inherit from that with your class template. That's all.
As an example:

struct SomeBase {
    enum SomeEnum { SOME_FLAG };
};

template<typename>
struct SomeClass: SomeBase {
    // ...
};

使用此:

SomeBase::SomeEnum::SOME_FLAG;

代替此:

SomeClass::SomeEnum::SOME_FLAG;

每当您想直接访问枚举时。

类似于以下内容反正仍然有效:

Whenever you want to access the enum directly.
Something like the following remains valid anyway:

SomeClass<void>::SomeEnum foo = SomeClass<void>::SomeEnum::SOME_FLAG;

这篇关于C ++-使用没有模板参数的模板类中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆