具有嵌套模板的C ++ typedef不是类,结构或联合类型

时间:2012-07-10 09:28:23

标签: c++ templates typedef typename

我不确定为什么以下代码不是用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

我希望能够在嵌套模板中传播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;
}

4 个答案:

答案 0 :(得分:4)

Distrib模板中,您有以下typedef

typedef typename SOLT::AtomType AtomType;

这意味着您作为模板参数传递的任何类型都必须有AtomType作为成员,double没有这样的内容。

如果你创建了这样的课程

class Double
{
   typedef myType AtomType;
};

并将其作为模板参数传递给您的Distrib模板,它会编译,因为Double::AtomType确实存在。

答案 1 :(得分:2)

Sampler课程中,您有:

typedef typename Distrib<AtomType>::Matrix Matrix;

此处AtomTypedouble,因此

typedef typename Distrib<double>::Matrix Matrix;

然后在你的Distrib课程中,

typedef typename SOLT::AtomType AtomType;

扩展为

typedef typename double::AtomType AtomType;

因此出现错误消息。我想你希望Sampler类中的行是:

typedef typename DT::Matrix Matrix;

答案 2 :(得分:1)

Matrix类中的Distrib typedef正在使用AtomType,但我们期望的是DT

typedef typename Distrib<DT>::Matrix Matrix;

编译器看到double在嵌套模板中传播。

答案 3 :(得分:1)

Distrib模仿Solution的类型;但是在Sampler::Matrix的定义中,您使用AtomType作为模板参数。据推测,您只需要提供Distrib所提供的Sampler类型:

template<typename DT>
class Sampler
{
    // ...
    typedef typename DT::Matrix Matrix;
};