问题描述
我有以下代码:
template<typename T, typename Allocator = std::allocator<T> >
class Carray {
// ...
typedef T* pointer;
typedef pointer iterator;
// ...
};
现在我试图对进行部分专门化iterator_traits
。对我来说似乎确定,但g ++ 4.4.5抱怨:
Now I'm trying to do partial specialization for iterator_traits
. It seems OK to me, but g++ 4.4.5 complains:
#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;
};
}
这是完整的错误信息:
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
推荐答案
所有这里: iterator_traits
已经专门用于指针类型,如果你最终得到一个类型的迭代器,你可以只需要定义那些 typedef
在迭代器类中。
You shouldn't need a specialization at all here: iterator_traits
is already specialized for pointer types and if you do end up with an iterator that is a class type, you can just define those required typedef
s in the iterator class.
问题是为了匹配主要的专业化,编译器需要
The problem is that in order to match the primary specialization, the compiler needs to take the arguments with which the template is used, plug them into the specialization, and see whether they match.
考虑在以下简化方案中会发生什么:
Consider what would happen in the following simplified scenario:
template <typename T> struct S { typedef int type; };
template <typename T>
struct Traits { };
template <typename T>
struct Traits<typename S<T>::type> { };
编译器应该如何知道 T
插入 S
或是否有一些 S :: type
真的意味着而不是只是 int
?
How is the compiler supposed to know what T
to plug into S
or whether some S<T>::type
is really meant instead of just int
?
问题是嵌套的typedef( :: type
)取决于模板参数( T
)。当在函数参数列表或部分专业化中是这种情况时,不能推导出类型 T
(它是一个非推导的上下文)。
The problem is that the nested typedef (::type
) depends on the template parameter (T
). When this is the case in a function argument list or in a partial specialization, the type T
cannot be deduced (it is a "non-deduced context").
这篇关于模板参数未在部分专业化中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!