簡體   English   中英

具有嵌套模板的C ++ typedef不是類,結構或聯合類型

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

我不確定為什么以下代碼不是用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作為模板參數。 據推測,您只需要為Sampler提供的Distrib類型:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM