该类std::vector<T>
是 STL Container 概念的模型,因此任何适当的 vector 实现都必须包含嵌套的 typedefvalue_type
以及reference
. 这应该可以使用 SFINAE 检测到。但是,在我自己的测试中,我可以使用 SFINAE 来检测嵌套的value_type
typedef,但由于某种原因我无法检测到reference
.
template <class T>
typename T::value_type* test(T)
{
cout << "Has nested typedef!" << endl;
}
template <class T>
void test(...)
{
cout << "Doesn't have nested typedef!" << endl;
}
int main()
{
test(std::vector<int>());
}
这输出:Has nested typedef!
但是,如果我用 替换value_type
,reference
例如:
template <class T>
typename T::reference* test(T)
{
cout << "Has nested typedef!" << endl;
}
template <class T>
void test(...)
{
cout << "Doesn't have nested typedef!" << endl;
}
int main()
{
test(std::vector<int>());
}
...程序根本无法编译,出现错误:error: no matching function for call to test(std::vector<int, std::allocator<int> >)
为什么 SFINAE 技术适用于T::value_type
而不适用于T::reference
?