c++ - SFINAE 未检测到 T::reference

标签 c++ stl sfinae

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_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

最佳答案

什么是指向引用的指针?

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

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

关于c++ - SFINAE 未检测到 T::reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5838895/

相关文章:

c++ - 如何使用 C++ 计算 1-100 数组中的覆盖百分比?

c++ - 假设 sizeof(std::unordered_map<std::string, T>) 对于所有 T 都相同实际上是安全的吗?

c++ - 如何注入(inject)模拟对象?

C++检查回文时如何忽略上下的区别?

c++ - 如何比较/排序包含自定义 typedef 的列表容器的元素?

c++ - SFINAE 在 decltype 中使用范围解析运算符

c++ - SFINAE 优雅地检查 "template template class"(在模板参数中)

c++ - 如何编写一个模板函数,它接受一个数组和一个指定数组大小的 int

c++ - 继承和虚函数与泛型编程