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

标签 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;
}

最佳答案

在您的 Distrib 模板中,您有以下 typedef

typedef typename SOLT::AtomType AtomType;

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

如果你像这样创建一个类

class Double
{
   typedef myType AtomType;
};

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

关于带有嵌套模板的 C++ typedef 不是类、结构或 union 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11410350/

相关文章:

c++ - 如何在 COM 对象 idl 中声明 typedef?

c++ - QPainter::begin 在 Debug模式下使程序崩溃

c++ - 从文件读取后输出中有额外的零行

c++ - 没有函数模板 "max"的实例匹配参数列表参数类型是 (int, int)

c++ - 模板类中的 is_foo 结构

c - 声明两个不同的结构大小

c++ - 在 C++ 中进行 protected 成员可访问性额外检查的原因是什么?

c++ - 我正在计算文件中的字符数,但我想计算小于 5 和 6 或更大的单词数

c++ - 为模板类编写二元加法运算符。编译错误

c - 如何在没有警告的情况下处理这些 typedef?