将内部类与CRTP一起使用 [英] Using inner class with CRTP

查看:42
本文介绍了将内部类与CRTP一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将内部类或枚举与CRTP一起使用?例

Is there any possibility to use inner class or enum with CRTP? Ex.

template<typename Container>
struct ContainerBase
{
    std::map<typename Container::Enum, int> _;
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{
    enum class Enum
    {
        left,
        right
    };
};

推荐答案

否.在类模板中,派生类尚未完全定义(这不是 standardese 中的完整对象).
事实上(工作草案):

No. Within the class template the derived class isn't fully defined yet (that's not a complete object in standardese).
In fact (working draft):

在结束}

因此,您不能期望能够从类模板中访问成员之一或在派生类中声明的任何对象.

Therefore you cannot expect to be able to access one of the members or whatever you declared in the derived class from within the class template.

您可以通过分别传递枚举来解决它,但是它要求您在其他地方定义枚举(另一个基类?外部作用域?任何...).您可以使用traits类来解决.依此类推.
有几种替代方法,但是您不能直接访问派生类中定义的枚举.
这是一个可行的解决方案的示例:

You can work around it by passing the enum separately, but it requires you to define the enum somewhere else (Another base class? The outer scope? Whatever...). You can work around by using traits classes. And so on.
There are several alternatives to do that, but you cannot access directly the enum defined in the derived class.
Here is an example of a viable solution:

#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 上运行它.

这篇关于将内部类与CRTP一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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