gpt4 book ai didi

c++ - CRTP 从基类引用派生类中的 typedef

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:23 26 4
gpt4 key购买 nike

我有以下代码:

template <typename T>
class A
{
typedef typename T::Type MyType;
};

template <typename T>
class B : public A<B<T>>
{
typedef T Type;
};

当我尝试实例化 B 时,我使用 MSVS 2015 收到以下错误消息:

'Type': is not a member of 'B<int>'

这段代码是有效的 C++ 还是 MSVS 正确?

最佳答案

问题就出在这里

template <typename T>
class A
{
typedef typename T::Type MyType;
^^^
};

T需要是一个完整的类型。但在你的情况下,当 A<T>在这里实例化:

template <typename T>
class B : public A<B<T>>
^^^^^^^

B<T>还不是一个完整的类型!不幸的是,这无法工作。

简单的解决方案就是传入Type分别:

template <typename T, typename Type>
class A
{
typedef Type MyType;
};

template <typename T>
class B : public A<B<T>, T>
{

};

关于c++ - CRTP 从基类引用派生类中的 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36268400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com