C++ 模板特化不适用于嵌套类型

C++ template specializations not working with nested types

以下代码可以编译,但无法运行:

template<typename T>
struct Nesting
{
    template<typename U>
    struct _Nested
    {
    };

    template<typename U>
    using Nested = _Nested<U>;
};

template<typename T>
struct F
{
    static constexpr bool is_my_nested_class = false;
};

template<typename T, typename U>
struct F<typename Nesting<T>::Nested<U>>
{
    static constexpr bool is_my_nested_class = true;
};

我创建了这些 Nesting 和 Nested 类型,并尝试在其上使用类型特征模式。它编译(使用带 CPP11 的 MSVC 2014),但是

F<Nesting<int>::Nested<long>>::is_my_nested_class

returns .

这是禁止的还是标准未定义的?它打破了什么规则?任何解决方法?

非常感谢!

您的嵌套别名可以引用任何类型,特别是在专业化中:

template<typename T>
struct Nesting
{
    template<typename U>
    struct _Nested
    {
    };

    template<typename U>
    using Nested = _Nested<U>;
};

// Consider this specialisation:
template<>
struct Nesting<int>
{
    template<typename U>
    using Nested = float;
};

现在,显然 F<Nesting<int>::Nested<int>>::is_my_nested_class 应该与 F<float>::is_my_nested_class 相同,但是,对于后一种情况,编译器如何推断出这一点?也就是说,如果我写:

static_assert(F<float>::is_my_nested_class, "not nested");

编译器需要看到 F<float>F<Nesting<int>::Nested<int>> 相同,即使后者尚未实例化。由于不能合理地期望这样做,因此不允许该案例。