【问题标题】:C++ typedef with nested templates is not a class, struct, or union type带有嵌套模板的 C++ typedef 不是类、结构或联合类型
【发布时间】:2012-07-10 09:28:22
【问题描述】:

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

【问题讨论】:

    标签: c++ templates typedef typename


    【解决方案1】:

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

    typedef typename SOLT::AtomType AtomType;
    

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

    如果你做了这样的课程

    class Double
    {
       typedef myType AtomType;
    };
    

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

    【讨论】:

    • 请注意,OP 将Solution&lt;double&gt; 作为参数传递给Distrib,但错误与传递double 本身相同。
    • 那仍然无法编译,即使编译也是错误的。问题是使用AtomType 作为Distrib 的模板参数,它需要某种Solution
    【解决方案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;
    

    【讨论】:

      【解决方案3】:

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

      typedef typename Distrib<DT>::Matrix Matrix;
      

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

      【讨论】:

      • 我认为您实际上并不需要 AtomType 的 typedef 才能在 Sampler 中声明矩阵。你可以简单地说typedef typename DT::Matrix matrix;,不是吗?
      • 不,Distrib 需要一个 Solution,而不是另一个 Distrib。我们没有,但由于DTDistrib,我们不需要它——它可能应该是typedef typename DT::Matrix matrix;
      【解决方案4】:

      Distrib 被模板化为Solution 的类型;但是在Sampler::Matrix 的定义中,您使用AtomType 作为模板参数。大概,您只想要Sampler 提供的Distrib 的类型:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        相关资源
        最近更新 更多