嵌套类型的CRTP

CRTP with nested type

本文关键字:CRTP 嵌套类型      更新时间:2023-10-16

我想创建一个模板类,为类提供通用方法,使其具有指定继承类提供的某种类型的成员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(而失败,这是可以理解的。我是遗漏了一些琐碎的东西,还是这只是一种错误的方法,我应该将嵌套的类型移到类之外(我只是希望类本身包含相关的类型,而不是填充更高的名称空间(。现场演示。

在声明struct Foo并从TypeAttribute继承时,Foo还不是一个完整的类型。与struct Bar相同
你的问题离这篇文章很近。

也许我做的这个代码可以帮助你实时演示

#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);
}