c++ - 使用默认参数专门化内部模板

标签 c++ templates specialization

当内部模板的参数都已知时,我在专门化内部模板时遇到了麻烦。这是一个例子:

template < typename T0 >
struct outer
{
    template < typename T1 = void, typename T2 = void >
    struct inner
    {
        typedef T1 type;
    };
};
template < typename T0 >
template < typename T1 >
struct outer<T0>::inner<double,T1> { typedef int type; };

这很好用。如果我改为像这样指定内部模板,它不会:

template < typename T0 >
template < >
struct outer<T0>::inner<double,void> { typedef int type; };

为此,我收到错误消息,“在‘>’标记之前无效的显式特化...封闭类模板未明确特化...模板参数未在部分特化中使用:...T0”。不确定 WTAF 是否在这里进行。

我也试过这个:

template < typename T0 >
struct outer<T0>::inner<double,void> { typedef int type; };

我预计这会失败并且错误消息并不奇怪。它是:“模板参数列表太少”。

那么,正确的做法是什么?我当然可以破解它,但如果我不必这样做,我宁愿不这样做。

最佳答案

这是不允许的。您无法完全特化本身尚未完全特化的类模板的成员。

根据 C++11 标准的第 14.7.16 段:

In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well. [...]

此外,C++11 标准的第 14.7.3/15 段说:

A member or a member template may be nested within many enclosing class templates. In an explicit specialization for such a member, the member declaration shall be preceded by a template<> for each enclosing class template that is explicitly specialized. [ Example:

template<class T1> class A {
     template<class T2> class B {
         void mf();
     };
};
template<> template<> class A<int>::B<double>;
template<> template<> void A<char>::B<char>::mf();

end example ]

关于c++ - 使用默认参数专门化内部模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129543/

相关文章:

c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”

c++ - 推导模板函数中的数组大小,传递值与传递引用的差值

scala - 如何使用 Scala 特化提供手动特化的实现?

c++ - 错误 : nested class in a nested class in a template class "is not a type"

c++ - 仅专门化模板类的一个方法(的一部分)

c++ - 为什么我自定义的 `::swap` 函数没有被调用?

c++ - boost 和单线程事件驱动模型

c++ - 通过 SWIG 从 Ruby 调用 Boost?

c++ - Visual C++ x64 带进位加法

c++ - 从函数指针创建 boost::function 的跨平台方式