在 CRTP 中使用内部 class
Using inner class with CRTP
有没有可能在 CRTP 中使用内部 class 或枚举?例如
template<typename Container>
struct ContainerBase
{
std::map<typename Container::Enum, int> _;
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{
enum class Enum
{
left,
right
};
};
没有。在 class 模板中,派生的 class 尚未完全定义(在 standardese 中这不是一个完整的对象)。
In fact(工作草案):
A class is considered a completely-defined object type (or complete type) at the closing }
因此,您不能指望能够从 class 模板中访问其中一个成员或您在派生 class 中声明的任何内容。
您可以通过单独传递枚举来解决它,但它需要您在其他地方定义枚举(另一个基础 class?外部范围?随便...)。您可以使用 traits classes 来变通。等等。
有几种方法可以做到这一点,但您不能直接访问派生 class.
中定义的枚举
这是一个可行解决方案的示例:
#include <map>
template<typename> struct traits;
template<typename Container>
struct ContainerBase
{
std::map<typename traits<Container>::Enum, int> _;
};
template<>
struct traits<struct ConcreteContainer> {
enum class Enum
{
left,
right
};
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{};
int main() {
ConcreteContainer cc;
cc._[traits<ConcreteContainer>::Enum::left] = 0;
cc._[traits<ConcreteContainer>::Enum::right] = 1;
}
在 wandbox 上查看并 运行。
有没有可能在 CRTP 中使用内部 class 或枚举?例如
template<typename Container>
struct ContainerBase
{
std::map<typename Container::Enum, int> _;
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{
enum class Enum
{
left,
right
};
};
没有。在 class 模板中,派生的 class 尚未完全定义(在 standardese 中这不是一个完整的对象)。
In fact(工作草案):
A class is considered a completely-defined object type (or complete type) at the closing
}
因此,您不能指望能够从 class 模板中访问其中一个成员或您在派生 class 中声明的任何内容。
您可以通过单独传递枚举来解决它,但它需要您在其他地方定义枚举(另一个基础 class?外部范围?随便...)。您可以使用 traits classes 来变通。等等。
有几种方法可以做到这一点,但您不能直接访问派生 class.
中定义的枚举
这是一个可行解决方案的示例:
#include <map>
template<typename> struct traits;
template<typename Container>
struct ContainerBase
{
std::map<typename traits<Container>::Enum, int> _;
};
template<>
struct traits<struct ConcreteContainer> {
enum class Enum
{
left,
right
};
};
struct ConcreteContainer : ContainerBase<ConcreteContainer>
{};
int main() {
ConcreteContainer cc;
cc._[traits<ConcreteContainer>::Enum::left] = 0;
cc._[traits<ConcreteContainer>::Enum::right] = 1;
}
在 wandbox 上查看并 运行。