Error: class template partial specialization contains a template parameter that cannot be deduced

Error: class template partial specialization contains a template parameter that cannot be deduced

我很感激帮助弄清楚我的代码中出现的这个问题是怎么回事,我已将其简化为以下内容:

typedef unsigned short ushort;

template<typename T = ushort*>
struct Foo
{
};

// Specialization -- works when not a specialization
template<
    template<typename,typename> class Container ,
    template<typename , template<typename,typename> class> class MetaFunction
    >
struct Foo<Container<ushort,typename MetaFunction<ushort,Container>::Type> >
{   
    //typedef Container<ushort,typename MetaFunction<ushort,Container>::Type> TestType; // OK
};

int main()
{
}

在编译 (gcc 5.4.0) 时出现错误:

Test.cpp:14:8: error: template parameters not deducible in partial specialization:
 struct Foo<Container<ushort,typename MetaFunction<ushort,Container>::Type> >
        ^
Test.cpp:14:8: note:         ‘template<class, template<class, class> class<template-parameter-2-2> > class MetaFunction’

奇怪的是,关于专业化的论点 Container<ushort,typename MetaFunction<ushort,Container>::Type> 似乎是有效的。

这里的问题是

MetaFunction<ushort,Container>::Type

是一个 非推导上下文 ,换句话说,编译器无法从中推导出模板参数,因此您的特化无效。要了解原因,请从之前的 SO 问题中阅读更多相关信息

What is a nondeduced context?

基本上,非推导上下文归结为

template<typename T>
struct Identity
{
    using type = T;
};

现在,在像 Identity<T>::type 这样的模式中,不会推导出 T,尽管对您来说它可能看起来很明显(再次参见 link 中的示例,我提供了原因是这样的,它与部分专业化以及类型和专业化成员之间缺乏 1-1 对应关系有关。