部分特化中未使用的模板参数

orl*_*rlp 4 c++ partial-specialization iterator-traits

我有以下代码:

template<typename T, typename Allocator = std::allocator<T> >
class Carray {
    // ...
    typedef T* pointer;
    typedef pointer iterator;
    // ...
};
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试进行部分专业化iterator_traits.对我来说似乎没问题,但g ++ 4.4.5抱怨:

#include <iterator>

namespace std {
    template<typename T, typename Allocator>
    struct iterator_traits<typename Carray<T, Allocator>::iterator> { // line 128
        typedef T value_type;
        typedef typename Allocator::difference_type difference_type;
        typedef typename Allocator::reference reference;
        typedef typename Allocator::pointer pointer;
        typedef typename std::random_access_iterator_tag iterator_category;
    };
}
Run Code Online (Sandbox Code Playgroud)

这是完整的错误消息:

carray.h:128: error: template parameters not used in partial specialization:
carray.h:128: error:         ‘T’
carray.h:130: error: ‘Allocator’ has not been declared
carray.h:131: error: ‘Allocator’ has not been declared
carray.h:132: error: ‘Allocator’ has not been declared
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 10

在这里你根本不需要专门化: iterator_traits已经专门用于指针类型,如果你最终得到一个类类型的迭代器,你可以typedef在迭代器类中定义那些必需的.

问题是,为了匹配主要特化,编译器需要获取使用模板的参数,将它们插入特化,并查看它们是否匹配.

考虑以下简化方案中会发生什么:

template <typename T> struct S { typedef int type; };

template <typename T> 
struct Traits { };

template <typename T> 
struct Traits<typename S<T>::type> { };
Run Code Online (Sandbox Code Playgroud)

编译器应该如何知道T要插入什么S或者是否S<T>::type真的意味着int什么呢?

问题是嵌套的typedef(::type)取决于模板参数(T).如果是函数参数列表或部分特化中的情况,T则无法推导出类型(它是"非推导的上下文").