【发布时间】:2013-03-25 12:50:57
【问题描述】:
我正在使用两个辅助结构来处理智能指针和向量
template<typename T>
struct Pointer {
typedef shared_ptr<T> type;
};
template<typename T>
struct Vector {
typedef vector<T, allocator<T>> type;
};
在这种情况下是很明显的表达方式
is_same<
vector<
shared_ptr<T>,
allocator<shared_ptr<T>>>,
Vector<
Pointer<T>::type>::type>
::value
为真。但是我现在有一个模板函数(实际上是一个操作符),在使用 Vector<Pointer<T>::type>::type 或通常的 vector 时处理方式不同:
// (1) General version
template<typename T>
Foo& operator&(T& object);
// (2a) Specialized version
template<typename T>
Foo& operator&(vector<shared_ptr<T>, allocator<shared_ptr<T>>>& object);
// (2b) Specialized version which does not work
template<typename T>
Foo& operator&(typename Vector<typename Pointer<T>::type>::type& object);
当我的代码中有 (2a) 时调用此运算符按预期工作。但是,当我将 (2a) 替换为 (2b) 时,编译器/链接器会尝试将调用与 (1) 匹配,这对我来说会产生链接错误,因为 (1) 未定义/对向量有效。为什么编译器对 (2a) 和 (2b) 的处理方式不同?
【问题讨论】:
-
那些
typenames 是2b的必需品吗? -
您无需将
allocator模板参数指定给vector。默认情况下,它将与您声明的完全一样。 -
@jt234:IntelliSense 和编译器抱怨没有
typename和dependent name is not a type,并建议我使用关键字。
标签: c++ templates stl typedef template-specialization