SFINAE未检测到T :: reference

Cha*_*l72 4 c++ stl sfinae

std::vector<T>类是STL容器概念的模型,并且作为载体的例如任何适当的实现必须包括一个嵌套的typedef value_type以及reference.这应该可以使用SFINAE检测到.但是,在我自己的测试中,我可以使用SFINAE来检测嵌套的value_typetypedef,但由于某些原因我无法检测到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>());
}
Run Code Online (Sandbox Code Playgroud)

这输出: Has nested typedef!

不过,如果我取代value_typereference,如:

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>());
}
Run Code Online (Sandbox Code Playgroud)

...程序根本无法编译,给出错误: error: no matching function for call to test(std::vector<int, std::allocator<int> >)

为什么SFINAE技术可以使用T::value_type但不适用T::reference

Lig*_*ica 5

什么是引用的指针?

:不可能.引用的指针不可存在,因此您的任何函数都不存在.这与您的第一种情况形成对比,其中至少有一种功能可以存在(因此您可以获得编译,链接和输出).

有趣的是,SFINAE 这里工作,因为函数定义不会导致编译错误.它试图调用一个函数,因为不可能+ SFINAE,不存在,导致错误.:)