在类模板中找不到声明的类型

Declared type not found in class template

本文关键字:声明 类型 找不到      更新时间:2023-10-16

如果您能帮助我解决以下错误,我将不胜感激。我得到了一个"在struct Frobnigator<Foo>错误中找不到类型Attributes",即使结构Frobigator声明了这样的成员,如下所示(另请参阅ideone.com)。

struct Foo{};
struct Bar{};
/////////////////////////////////////////////////////////////////////////////
template<typename P>
struct Attributes
{
};
template<>
struct Attributes<Foo>
{
};
/////////////////////////////////////////////////////////////////////////////
template<typename P>
struct Frobnigator
{
    Attributes<P>   attributes;
};
/////////////////////////////////////////////////////////////////////////////
template<typename P>
struct OuterHandler
{
    typedef Frobnigator<P>  Frob;
    template<typename T>
    struct InnerHandler;
    void doStuff();
};
template<>
struct OuterHandler<Foo>
{
    typedef Frobnigator<Foo>    Frob;
    template<typename T>
    struct InnerHandler;
    void doStuff();
};
/////////////////////////////////////////////////////////////////////////////
template<typename P>
template<typename T>
struct OuterHandler<P>::InnerHandler
{   
    typename T::Attributes attributes;
    InnerHandler(){}
};

template<typename T>
struct OuterHandler<Foo>::InnerHandler
{
    typename T::Attributes attributes;
    InnerHandler(){}
};
/////////////////////////////////////////////////////////////////////////////
template<typename P>
void OuterHandler<P>::doStuff()
{
    InnerHandler<Frob>();
}
void OuterHandler<Foo>::doStuff()
{
    InnerHandler<Frob>();
}
/////////////////////////////////////////////////////////////////////////////
int main()
{
    return 0;
}
/////////////////////////////////////////////////////////////////////////////

Visual studio错误消息

Test.cpp(62) : error C2039: 'Attributes' : is not a member of 'Frobnigator<P>'
        with
        [
            P=Foo
        ]
        Test.cpp(76) : see reference to class template instantiation 'OuterHandler<Foo>::InnerHandler<T>' being compiled
        with
        [
            T=OuterHandler<Foo>::Frob
        ]

g++(GCC)4.5.3错误消息

Test.cpp: In instantiation of ‘OuterHandler<Foo>::InnerHandler<Frobnigator<Foo> >’:
Test.cpp:76:21:   instantiated from here
Test.cpp:62:25: error: no type named ‘Attributes’ in ‘struct Frobnigator<Foo>’

什么令人困惑?Frobnigator<T>实际上没有名为Attributes的类型成员。

如果您使用的是C++11,请尝试:

typename decltype(T::attributes) attributes;

否则,可能更清楚:

template<typename P>
struct Frobnigator
{
    typedef Attributes<P> attributes_type;
    attributes_type attributes;
};

然后您可以在任何地方使用Frobnigator<T>::attributes_type

如果我理解得对,您正在寻找与Boost中的graph_traits<Graph>类似的实现。

#include <iostream>
using namespace std;
struct Foo {};
template<typename T>
struct Attributes
{
};
template<>
struct Attributes<Foo>
{
};
template<typename T>
struct Frobnigator
{
  typedef Attributes<T> Attr;
  Attr attributes;
};
template<typename T>
struct traits
{
  typedef typename T::Attr Attributes;
};
int main()
{
  traits<Frobnigator<Foo> >::Attributes a;
  return 0;
}