首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套型CRTP

嵌套型CRTP
EN

Stack Overflow用户
提问于 2015-08-07 11:33:01
回答 1查看 808关注 0票数 2

我想要创建一个模板类,它将为类提供泛型方法,使类有一个成员m_Type来指定继承类提供的某种类型。考虑到这一点:

代码语言:javascript
复制
template<typename T>
struct TypeAttribute
{
    T m_Type;
};

template<typename T>
struct TypeAttribute2
{
    using Type = typename T::Type;
    Type  m_Type;
};

struct Foo : TypeAttribute<Foo::Type>
{
    enum class Type
    {
        Type1
    };
};

struct Bar : TypeAttribute2<Bar>
{
    enum class Type
    {
        Type1
    };
};

这两种类型都由于类型不完整而失败(在第一种情况下是Foo::Type,在第二种情况下是Bar::Type),这是可以理解的。我是遗漏了一些琐碎的东西,还是这只是一种错误的方法,我应该将嵌套类型移到类之外(我只是希望类内部包含相关类型,而不是填充更高的命名空间)。现场演示

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-07 15:21:43

在声明struct Foo并从TypeAttribute继承时,Foo还不是一个完整的类型。struct Bar也一样。

您的问题与这个帖子非常接近。

也许我编写的这段代码可以帮助您现场演示

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <memory>

enum class ChildType
{
    Child1,
    Child2
};

template <typename Derived>
struct Parent
{
    void DisplayChildType() const
    {
        switch (Derived::type_)
        {
            case ChildType::Child1: std::cout << "Child1" << std::endl; break;
            case ChildType::Child2: std::cout << "Child2" << std::endl; break;
            default:;
        }
    }
};

struct Child1 : Parent<Child1>
{
    static constexpr ChildType type_ = ChildType::Child1;
};

struct Child2 : Parent<Child2>
{
    static constexpr ChildType type_ = ChildType::Child2;
};

template <typename Type>
void DisplayType(const Type& child)
{
    const Parent<Type>* asParent = &child;
    asParent->DisplayChildType();
}

int main()
{
    Child1 child1;
    Child2 child2;

    DisplayType(child1);
    DisplayType(child2);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31876721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档