我想要创建一个模板类,它将为类提供泛型方法,使类有一个成员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),这是可以理解的。我是遗漏了一些琐碎的东西,还是这只是一种错误的方法,我应该将嵌套类型移到类之外(我只是希望类内部包含相关类型,而不是填充更高的命名空间)。现场演示。
发布于 2015-08-07 15:21:43
在声明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);
}https://stackoverflow.com/questions/31876721
复制相似问题