【问题标题】:MSVC 2008 error 'Type' is not a struct (although it is)MSVC 2008 错误“类型”不是结构(尽管它是)
【发布时间】:2015-01-08 08:18:20
【问题描述】:

以下 MWE 在 gcc 4.8.2 上编译,但在 MSVC 2008 上不编译(公司政策)

struct B
{
};

struct A
{
    typedef B Handler;
};

template<typename T>
struct Foo
{
    typedef typename T::Handler  Type;
};

template<typename T>
struct Bar
{
    friend struct Foo<T>::Type;     // MSVC 2008 does not like this
    typedef typename Foo<T>::Type   Foo;
};

int main() 
{
}

MSVC 2008 错误

error C2649: 'Foo<T>::Type' : is not a 'struct'

这是一个编译器错误还是我在这里做了非法的事情?更重要的是有解决办法吗?

【问题讨论】:

标签: c++ templates visual-c++ language-lawyer friend


【解决方案1】:

去掉struct关键字,用typename代替:

template<typename T>
struct Bar
{
    friend typename Foo<T>::Type;     
    typedef typename Foo<T>::Type   Foo;
};

【讨论】:

  • (Un)幸运的是compiles在VC++上也没有typename,可能是编译器错误?
【解决方案2】:

好像无效。 [class.friend]/3:

一个没有声明函数的friend声明应该有一个 以下形式:
friend 详细类型说明符;
friend 简单类型说明符;
friend 类型说明符 em>;

但是,对详细类型说明符有一个重要限制:[dcl.type.elab]/2:

如果标识符解析为 typedef-name […] 详细类型说明符格式不正确。

在这方面,GCC 和 Clang 是错误的,而令人惊讶的是,VC++ 是正确的。
您可以利用第一个引号的第三个项目符号并使用类型名称说明符。

friend typename Foo<T>::Type;

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 2018-10-26
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多