CRTP具有嵌套类型

时间:2015-08-07 11:33:01

标签: c++ templates crtp

我想创建一个模板类,它将为类提供通用方法,使其具有成员m_Type,该成员指定继承类提供的某种类型。考虑一下:

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),这两种情况都会失败,这是可以理解的。我错过了一些微不足道的东西,或者这只是一个错误的方法,我应该在类之外移动嵌套类型(我只是希望类本身包含相关类型,而不是填充更高的命名空间)。 Live demo here

1 个答案:

答案 0 :(得分:1)

当您声明struct Foo并继承TypeAttribute时,Foo还不是完整类型。 struct Bar相同。
您的问题非常接近post

也许我制作的这段代码可以帮助您Live Demo

#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);
}
相关问题