是否有可能在 CRTP 中使用内部类或枚举?前任。
template<typename Container>
struct ContainerBase
{
std::map<typename Container::Enum, int> _;
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{
enum class Enum
{
left,
right
};
};
不。在类模板中,派生类尚未完全定义(这不是一个完整的对象)标准语).
In fact(工作草案):
类在结束时被认为是完全定义的对象类型(或完整类型)}
因此,您不能期望能够从类模板中访问成员之一或您在派生类中声明的任何内容。
您可以通过单独传递枚举来解决这个问题,但它要求您在其他地方定义枚举(另一个基类?外部作用域?无论如何......)。您可以通过使用特征类来解决这个问题。等等。
有多种替代方法可以做到这一点,但您无法直接访问派生类中定义的枚举。
这是一个可行解决方案的示例:
#include <map>
template<typename> struct traits;
template<typename Container>
struct ContainerBase
{
std::map<typename traits<Container>::Enum, int> _;
};
template<>
struct traits<struct ConcreteContainer> {
enum class Enum
{
left,
right
};
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{};
int main() {
ConcreteContainer cc;
cc._[traits<ConcreteContainer>::Enum::left] = 0;
cc._[traits<ConcreteContainer>::Enum::right] = 1;
}
查看它的启动并运行wandbox.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)