在下面的程序中,尽管我有一个enable_if
语句将函数限制为整型容器类型,但这两个函数调用都会打印“非整型超载”。这是为什么?为什么重载分辨率选择第一个函数?
#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<...>>
但无济于事。
+1仅用于* C++ 03编译的解决方案。好吧,无论如何,C++ 03 + TR1。 – Casey