std::vector<T>
class 是 STL Container 概念的模型,因此 vector 的任何正确实现都必须包含嵌套的 typedef value_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
?
最佳答案
什么是指向引用的指针?
答:不可能。指向引用的指针不存在,因此您的两个函数都不存在。这与您的第一种情况形成对比,在第一种情况下,至少可以存在一个函数(因此您可以获得编译、链接和输出)。
有趣的是,SFINAE 正在在这里工作,因为函数定义不会导致编译错误。它试图调用一个函数,由于不可能+SFINAE,它不存在,这导致了错误。 :)
关于c++ - SFINAE 未检测到 T::reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5838895/