嵌套类显式规范:不同的编译器行为

Con*_*tor 9 c++ templates template-specialization language-lawyer explicit-specialization

以下代码使用clang ++ 6.0.0g ++ 7.3.0(编译标志-std=c++14 -Wall -Wextra -Werror -pedantic-errors)编译好,但无法使用vc ++编译19.10.25017(编译标志为/Za):

template <typename>
struct A
{
    template <typename>
    struct B
    {
    };
};

template <>
template <>
struct A<int>::B<char>
{
    static void foo();
};

void A<int>::B<char>::foo()
{
}

int main()
{
}
Run Code Online (Sandbox Code Playgroud)

vc ++编译错误消息:

错误C2906:'void A <int> :: B <char> :: foo(void)':显式特化需要'template <>'

在这种情况下,符合标准的行为是什么?

Col*_*mbo 4

VC++是错误的。可能会误解以下条款

显式专用类模板的成员的定义方式与普通类的成员相同,但不使用语法template<> 。定义显式专用成员类 (*) 的成员时也是如此。但是,template<>用于定义专门化为类模板的显式专门化成员类模板的成员。

后一条规则的目的是消除歧义:

// Which template does this header appertain to?
template<class U> void A<short>::C<U>::f() { /* ... */ } 
Run Code Online (Sandbox Code Playgroud)

但是,对于您的情况,(*) 情况适用。