我试图has_equal_operator在C++ 11中实现,到目前为止提出了以下解决方案.它适用于简单的情况,如int或struct A{}但失败(返回误报)std::vector<A>.为什么失败以及如何解决这个问题?
#include <vector>
#include <iostream>
template<typename T>
constexpr auto has_equal_operator(int) -> decltype(std::declval<T>() == std::declval<T>(), bool()) { return true; }
template<typename T>
constexpr bool has_equal_operator(...) { return false; }
struct A {};
void test()
{
std::cout << "has_equal_operator<int>: " << has_equal_operator<int>(0) << std::endl;
std::cout << "has_equal_operator<A>: " << has_equal_operator< A >(0) << std::endl;
std::cout << "has_equal_operator<std::vector<A>>: " << has_equal_operator< std::vector<A> >(0) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
has_equal_operator<int>: 1
has_equal_operator<A>: 0
has_equal_operator<std::vector<A>>: 1
Run Code Online (Sandbox Code Playgroud) C++参考清楚地声明调用std::vector::erase(it)迭代器将使指向擦除元素和擦除元素之后的所有迭代器无效.http://en.cppreference.com/w/cpp/container/vector/erase
我确实理解为什么这些迭代器在erase调用后变得不可解除引用,但我很好奇为什么它们需要变得无效,实现细节需要什么呢?
例如,标准说std::vector必须使用连续存储的元素来实现,elements can be accessed not only through iterators, but also using offsets on regular pointers to elements因此这样的容器的迭代器可能实现为指针似乎是合乎逻辑的 - 但是指针如何变得无效?