Sva*_*zen 1 c++ templates iterator sfinae c++11
我正在编写一个使用迭代器的算法函数.这个函数应该适用于普通和常量迭代器,重要的是这些迭代器来自的类不是模板,我事先就知道了.
有没有办法在以下定义中强制执行迭代器来自特定的类?
// This is an example, A could be any other class with exposed iterators.
using A = std::vector<int>;
// How to enforce that Iterator is an iterator from A?
template <typename Iterator>
Iterator foo(Iterator begin, Iterator end);
...
A a;
auto it = foo(a.begin(), a.end());
*it = 4; // Must compile
// --------
const A a;
auto it = foo(a.begin(), a.end());
*it = 4; // Must not compile
// --------
B b;
auto it = foo(b.begin(), b.end()); // Should not compile.
Run Code Online (Sandbox Code Playgroud)
在这种情况下,foo不直接修改提供的范围,但如果首先提供的范围是可修改的,则允许修改结果迭代器.如果可以在不复制代码的情况下完成这将是很好的.
只是不要使用模板:
A::iterator foo(A::iterator begin, A::iterator end);
Run Code Online (Sandbox Code Playgroud)