g++中的显式模板专用化导致问题

Explicit template specialization in g++ causing troubles

本文关键字:专用 问题 g++      更新时间:2023-10-16

我在将这段代码从MSVC:转换为g++时遇到了问题

#include <unordered_map>
class A
{
    template <class T> class B;
    template<>
    class A::B<int>
    {
    };
    std::unordered_map<int, long, B<int>> m_Map;
};

当然,这不是标准的c++,而VS仍然允许它GCC(g++)抛出一个错误"非命名空间范围中的显式专门化"。现在,我根据引用使其符合c++http://en.cppreference.com/w/cpp/language/template_specialization:

#include <unordered_map>
class A
{
    template <class T> class B;
    template <> class B<int>;
    std::unordered_map<int, long, B<int>> m_Map;
};
template<>
class A::B<int>
{
    std::size_t operator()(int const& n) const {
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    return 0;
}

唉,现在VS给了我一个错误

Error   3   error C2079: 'std::_Hash_oper1<true,_Hasher>::_Hashobj' uses undefined class 'A::B<int>'    c:program files (x86)microsoft visual studio 12.0vcincludexhash

 Error  2   error C2139: 'A::B<int>' : an undefined class is not allowed as an argument to compiler intrinsic type trait '__is_empty'   c:program files (x86)microsoft visual studio 12.0vcincludetype_traits

因此,无序映射定义不希望使用它认为的"未定义类"。尽管我提前宣布了。有人知道这是怎么回事吗?非常感谢。

标准库容器不能用不完整的类型声明为包含的类型。这会导致不需要诊断的未定义行为(这意味着一些编译器可能会接受它,而有些编译器可能会拒绝它或在运行时表现异常)。

您必须使用来自不同库(例如boost)的支持不完整类型的哈希表,或者重新设计代码。

一个简单的修复方法是首先使类B不在A内声明