嵌套类型的CRTP
CRTP with nested type
我想创建一个模板类,为类提供通用方法,使其具有指定继承类提供的某种类型的成员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);
}
相关文章:
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 为什么在VS2015中模板相关的嵌套类型名称中不需要typename关键字?
- 为什么嵌套类型的基类不需要"typename"?
- CRTP - 嵌套叶类类型的可见性
- 如何在C++中的另一个模板函数中使用属于模板化类的嵌套类型?
- 保持嵌套类型的挥发性
- 具有嵌套类型的类的概念
- 将嵌套类型的类分开为标题和源
- 如何解决C++嵌套类型的循环依赖关系
- 在 C++11 中,从私有嵌套类型继承是否合法?
- C++ 递归嵌套类型和名称注入
- 如何定义一个模板类函数,该函数在类外的签名中具有嵌套类型的模板参数
- 访问模板参数T的嵌套类型,即使T是指针
- 为什么reverse_iterator双重定义其嵌套类型
- 嵌套类型:结构与类
- 如何对嵌套类型执行部分模板专用化
- 如何解析可选的嵌套类型,如 std::allocator_traits
- 模板和嵌套类型查找
- C++ CRTP 并从 base 访问派生的嵌套类型定义
- 嵌套类型的CRTP