提问人:lequinne 提问时间:3/24/2023 更新时间:4/17/2023 访问量:91
强制使用枚举 c++ 的一个别名
Forcing usage of one alias of an enum c++
问:
我想为枚举提供多个别名,但在将枚举值传递给特定类时,强制调用代码使用一个特定的别名。这是我的好主意,但行不通:
template<typename Stype>
struct MoreDifferentS : Stype {};
struct S {
enum consumate {
v,
vv
};
};
class Dragon {
void Burn(S::consumate type) {};
public:
using mdS = MoreDifferentS<S>;
void Burn(mdS::consumate type) {};
};
//Usage:
Dragon d;
d.Burn(S::v); //I don't want this to compile
d.Burn(mdS::v); //I want this to compile
这样做的问题是,编译器仍然将两个函数视为采用相同的参数类型,并在我尝试调用 Burn(mdS::v) 时抛出“已定义或声明的成员函数”,或者抛出“函数 Burn(S::consumate) 不可访问”。 这周围有没有一些,或者我吠叫完全是错误的树?
谢谢
答:
1赞
lequinne
3/24/2023
#1
n.m. 建议强制 S 实例化为模板。这段代码完全实现了我想要的:
template<int>
struct S_Base {
enum consumate {
v,
vv
};
};
using S = S_Base<1>;
using mdS = S_Base<2>;
class Dragon {;
void Burn(S::consumate type) {};
public:
void Burn(mdS::consumate type) {};
};
//Usage:
Burn(S::v); //Doesn't compile
Burn(mdS::v); //Does compile
S 的两个不同派生类不会为 S 及其成员生成新类型,但两个不同的模板实例化会。
评论
S