Chr*_*vic 1 c++ templates stl typedef template-specialization
我使用两个辅助结构来处理智能指针和向量
template<typename T>
struct Pointer {
typedef shared_ptr<T> type;
};
template<typename T>
struct Vector {
typedef vector<T, allocator<T>> type;
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下,表达是显而易见的
is_same<
vector<
shared_ptr<T>,
allocator<shared_ptr<T>>>,
Vector<
Pointer<T>::type>::type>
::value
Run Code Online (Sandbox Code Playgroud)
收益真实.但是我现在有一个模板化的函数(实际上是一个oparator),在使用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);
Run Code Online (Sandbox Code Playgroud)
在我的代码中使用(2a)时调用此运算符按预期工作.然而,当我用(2b)替换(2a)时,编译器/链接器尝试将调用与(1)匹配,这对我产生链接错误,因为(1)没有定义/对于向量有效.为什么编译器对(2a)和(2b)的处理方式不同?
因为编译器无法推导出(2b)中的类型.问题是它可以匹配
vector<shared_ptr<T>,allocator<shared_ptr<T>>>
Run Code Online (Sandbox Code Playgroud)
因为那只是"只是一种类型"来匹配.对于任何给定的参数,它只检查是否存在T且类型匹配.编译器只需要测试一个选项.对于
typename Vector<typename Pointer<T>::type>::type
Run Code Online (Sandbox Code Playgroud)
编译器将不得不尝试所有Tfor Vector<...>::type将屈服于所需的类型,它不会.如果可能的话,该分析将比仅匹配直接类型更复杂.