[英]C++ typedef with nested templates is not a class, struct, or union type
I'm not sure to understand why the following code is not compiled with g++: 我不确定为什么以下代码不是用g ++编译的:
t.cpp: In instantiation of ‘Distrib<double>’:
t.cpp:28:56: instantiated from ‘Sampler<Distrib<Solution<double> > >’
t.cpp:35:48: instantiated from here
t.cpp:16:45: erreur: ‘double’ is not a class, struct, or union type
t.cpp:18:43: erreur: ‘double’ is not a class, struct, or union type
I was expecting to be able to propagate the AtomType
type across the nested templates… 我希望能够在嵌套模板中传播AtomType
类型...
#include <iostream>
#include <vector>
template<typename T>
class Solution
{
public:
typedef T AtomType;
};
template<typename SOLT>
class Distrib
{
public:
typedef typename SOLT::AtomType AtomType;
typedef std::vector<AtomType> Matrix;
Matrix matrix;
};
template<typename DT>
class Sampler
{
public:
typedef typename DT::AtomType AtomType;
typedef typename Distrib<AtomType>::Matrix Matrix;
Matrix matrix;
};
int main()
{
Sampler< Distrib< Solution<double> > > sampler;
}
In your Distrib
template you have the following typedef
在Distrib
模板中,您具有以下typedef
typedef typename SOLT::AtomType AtomType;
Which means that any type you pass in as a template parameter, must have a AtomType
as a member, and double
has no such thing. 这意味着您作为模板参数传入的任何类型都必须具有AtomType
作为成员,而double
具有此类内容。
If you made a class like so 如果你做了这样的课程
class Double
{
typedef myType AtomType;
};
and passed that in as a template parameter to your Distrib
template, it would compile, as Double::AtomType
does exist. 并将其作为模板参数传递给您的Distrib
模板,它将编译,因为Double::AtomType
确实存在。
In your Sampler
class, you have: 在Sampler
类中,您有:
typedef typename Distrib<AtomType>::Matrix Matrix;
Here, AtomType
is double
, so this is 在这里, AtomType
是double
,所以这是
typedef typename Distrib<double>::Matrix Matrix;
And then in your Distrib
class, the line 然后在你的Distrib
类中,该行
typedef typename SOLT::AtomType AtomType;
expands to 扩展到
typedef typename double::AtomType AtomType;
Hence the error message. 因此错误消息。 I think you want the line in the Sampler
class to be: 我想你希望Sampler
类中的行是:
typedef typename DT::Matrix Matrix;
The Matrix
typedef in the Distrib
class is using AtomType
, but what we would expect was a DT
: Distrib
类中的Matrix
typedef使用的是AtomType
,但我们期望的是DT
:
typedef typename Distrib<DT>::Matrix Matrix;
The compiler was seeing the double
propagated across nested templates. 编译器看到double
传播嵌套模板。
Distrib
is templated over the type of Solution
; Distrib
是关于Solution
类型的模板; but in the definition of Sampler::Matrix
you're using AtomType
as the template argument. 但在Sampler::Matrix
的定义中,您使用AtomType
作为模板参数。 Presumably, you just want the type of Distrib
that was provided as to the Sampler
: 据推测,您只需要为Sampler
提供的Distrib
类型:
template<typename DT>
class Sampler
{
// ...
typedef typename DT::Matrix Matrix;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.