gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:50 27 4
gpt4 key购买 nike

在下面的程序中,即使我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com