4

该类std::vector<T>是 STL Container 概念的模型,因此任何适当的 vector 实现都必须包含嵌套的 typedefvalue_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>());
}

这输出: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>());
}

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

为什么 SFINAE 技术适用于T::value_type而不适用于T::reference

4

2 回答 2

5

什么是指向引用的指针?

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

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

于 2011-04-30T01:44:43.670 回答
2

类型名 T::reference* test(T)

指向引用的指针在 C++ 中是非法的。

标准中的§8.3.2/4 说:

不能有对引用的引用,不能有引用数组,也不能有指向引用的指针。

于 2011-04-30T02:20:26.180 回答