使用别名(using)和typedef来访问C++中的嵌套类型

4
今天我们发现了一个令人困惑的C++11别名声明行为。 以下是示例:
template<typename T>
struct Q
{
    typedef T t;
};

template<typename T>
void foo(Q<T> q)
{
    using q_t = Q<T>; 
    //typedef Q<T> q_t; // if we uncomment this and comment 'using' the example compiles
    typename q_t::t qwe; // <<<<<<<<<< Error: no type named ‘t’ in ‘using q_t = struct Q<T>’
}

int main(int argc, char *argv[])
{
    Q<int> q;
    foo(q);
    return 0;
}

根据ISO 14882 (C++11)标准,这两个声明必须具有相同的语义(第145页)。

然而,如果我们使用'using'声明q_t,则在GCC 4.7.2(Debian Wheezy)和GCC 4.7.3(Ubuntu 13.04)上无法编译,但将'using'语句替换为'typedef'语句则可以编译。

这是GCC中的一个bug还是我们误解了标准?


1
它在gcc 4.8.1上运行良好。似乎是4.7版本中的一个错误。 - Angew is no longer proud of SO
2个回答

4

这似乎是GCC 4.7的一个bug。

这里是我的测试,使用gcc 4.8.1编译您的代码,它可以正常工作。

因此,正如规范所说:

using q_t = Q<T>;
// is equivalent to this 
typedef Q<T> q_t;

1

使用g++ 4.8.1编译时,--std=c++11选项可以正常编译。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接