Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 嵌套类型的CRTP_C++_Templates_Crtp - Fatal编程技术网

C++ 嵌套类型的CRTP

C++ 嵌套类型的CRTP,c++,templates,crtp,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 : TypeAt

我想创建一个模板类,该类将为类提供通用方法,使类具有指定继承类提供的某种类型的成员
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
    };
};
模板
结构类型属性
{
T型;
};
模板
结构类型属性2
{
使用Type=typename T::Type;
m_型;
};
结构Foo:TypeAttribute
{
枚举类类型
{
类型1
};
};
结构栏:TypeAttribute2
{
枚举类类型
{
类型1
};
};

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

在声明
struct Foo
并从
TypeAttribute
继承时,
Foo
还不是一个完整的类型。与结构栏相同
你的问题与此非常接近

也许我写的这个代码可以帮助你

#包括
#包括
#包括
枚举类子类型
{
孩子1,
孩子2
};
模板
结构父级
{
void DisplayChildType()常量
{
开关(派生::类型\)
{

case ChildType::Child1:std::cout正如我所说的,我知道这些类型是不完整的——我希望某种c++11魔法能够克服这一点。所以我只需要将枚举放在更高的范围内。
#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);
}