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

C++ typedef with nested templates is not a class, struct, or union type

本文关键字:结构 类型 嵌套 C++typedef      更新时间:2023-10-16

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

Distrib模板中,您有以下typedef

typedef typename SOLT::AtomType AtomType;

这意味着作为模板参数传入的任何类型都必须有一个AtomType作为成员,而double没有这样的东西。

如果你上了这样的课

class Double
{
   typedef myType AtomType;
};

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

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;

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

typedef typename Distrib<DT>::Matrix Matrix;

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

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

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