2011-06-18 45 views
3

我有以下代码:模板参数

template<typename T, typename Allocator = std::allocator<T> > 
class Carray { 
    // ... 
    typedef T* pointer; 
    typedef pointer iterator; 
    // ... 
}; 

现在我想为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; 
    }; 
} 

这是完全错误消息:

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 
+0

我不能重现这一点。你如何把它们放在一起? – Beta

+0

http://codepad.org/5gVzgYKc在Ubuntu 10.10上使用g ++ 4.4.5进行编译,完整命令:'g ++ test.cpp' – orlp

+0

您是否在头文件中定义了'Carray'文件,它专用于'iterator_traits'? – Nawaz

回答

9

你不应该需要一个专业化的一切都在这里: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> { }; 

如何编译器应该知道什么T插到S还是有些S<T>::type的真正含义,而不仅仅是int

问题是,嵌套typedef(::type)取决于模板参数(T)。当在函数参数列表或部分特化中出现这种情况时,不能推导出类型T(它是“非推导的上下文”)。

+0

那么为什么它在键盘上编译? – orlp

+0

键盘使用的是一个五年的编译器,可能是相当多的错误?我不知道;我的笔记本上没有旧的编译器。 g ++ 4.5.1和Visual C++ 2010 SP1都直接拒绝它;铿锵3.0r133044发出详细的警告,部分专业化将永远不会使用。 –

+0

Codepad.org是一个代码粘贴网站,它也可以编译您的代码进行测试,根据http://codepad.org/about使用g ++ 4.1.2和'-O -std = C++ 98 -pedantic - 错误 - 错误 - 错误 - 错误 - 错误 - 错误 - 缺少字段初始化器 - 写入字符串 - 错误 - 不推荐使用 - 错误 - 未使用 - 错误 - 非虚拟 - 错误 - 错误 - 错误 - 宏 - 错误 - 长度= 0 -ftemplate-depth-128 -fno-merge-constants -fno -nonansi-builtins -fno-gnu-keywords -fno-elide-constructors -fstrict-aliasing -fstack-protector-all -Winvalid -pch – orlp