c++ - 为什么重载决策不选择第一个函数?

标签 c++ c++11

在下面的程序中,即使我有一个 enable_if,两个函数调用都会打印“Non-integral overload”将函数限制为仅用于整型容器类型的语句。这是为什么?

#include <iostream>
#include <vector>
#include <type_traits>

template<bool B, typename V = void>
using enable_if = typename std::enable_if<B, V>::type;

template<typename ForwardIt>
auto f(ForwardIt first, ForwardIt)
    -> enable_if<std::is_integral<decltype(*first)>{}>
{
    std::cout << "Integral container type" << std::endl;
}

template<typename ForwardIt>
void f(ForwardIt, ForwardIt)
{
    std::cout << "Non-integral container type" << std::endl;
}

int main()
{
    struct X { };

    std::vector<int> iv;
    std::vector<X>   xv;

    f(iv.begin(), iv.end()); // "Non-integral container type"
    f(xv.begin(), xv.end()); // "Non-integral container type"
}

我什至尝试过使用 enable_if<!std::is_integral<...>>在第二次过载但无济于事。

最佳答案

另一个答案已经说明了问题,但我认为有更好的解决方案。

如果你想提取迭代器类型指向的类型,你应该使用iterator_traits .在您的代码中,将第一个重载更改为:

template<typename ForwardIt>
auto f(ForwardIt first, ForwardIt)
    -> enable_if<std::is_integral<typename std::iterator_traits<ForwardIt>::value_type>{}>
{
    std::cout << "Integral container type" << std::endl;
}

并在第二个上使用相同的附加 !。这更具描述性,因为代码非常清楚它的作用。

Live example

关于c++ - 为什么重载决策不选择第一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055403/

相关文章:

c++ - 可以使用 C++ 构建 Winforms 应用程序吗?

c++ - istringstream 不在变量中存储任何内容

c++ - perror 和 std::cerr 使用

c++ - Boost ASIO/Coroutines : Attempting to write an echo server using boost asio and coroutines, 但行为不一致

c++ - friend get 返回类型的函数,该函数通过可变参数模板递归计算

c++ - 多重声明与未定义

c++ - 将文件中的数据读取到结构中,对数据进行排序并写入文件

c++ - 通过 std::function 调用 std:make_shared

c++ - 在忽略默认参数的情况下从 lambda 函数中的模板参数调用静态函数

c++ - 保留集合中最小的 n 个元素,丢弃其他元素