强制使用枚举 c++ 的一个别名

Forcing usage of one alias of an enum c++

提问人:lequinne 提问时间:3/24/2023 更新时间:4/17/2023 访问量:91

问:

我想为枚举提供多个别名,但在将枚举值传递给特定类时,强制调用代码使用一个特定的别名。这是我的好主意,但行不通:

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) 不可访问”。 这周围有没有一些,或者我吠叫完全是错误的树?

谢谢

C++ 继承 枚举 scoped-enums

评论

1赞 NathanOliver 3/24/2023
别名就是这样,一个 alais。它没有引入新类型,只是同一类型的另一个名称。
0赞 lequinne 3/24/2023
是的。我正在寻找一种创建行为类似于新类型的别名的方法。或者换一种说法,创建我可以像别名一样编写的新类型,即定义它,而无需为每个新类型重新定义枚举成员。
2赞 n. m. could be an AI 3/24/2023
制作模板。S
0赞 lequinne 3/24/2023
@n这很有效,谢谢。你想把它作为答案发布,还是我应该?
1赞 n. m. could be an AI 3/24/2023
我总是鼓励自我回答;)

答:

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 及其成员生成新类型,但两个不同的模板实例化会。