我必须实现一个带迭代器的函数.迭代器必须取消引用某个类型,比如int:
template<typename iter>
void f(iter i) {
// do something here ...
int t = *i;
// do something here ...
}
Run Code Online (Sandbox Code Playgroud)
这段代码的问题在于,如果用户调用这样的函数
vector<string> v;
v.push_back("aaa");
f(v.begin());
Run Code Online (Sandbox Code Playgroud)
他会看到错误指向我的代码中的某个位置,而不是他的代码(这会让他感到困惑).我希望错误出现在用户代码中以简化调试.
GMan已经指出了一种通过编译时断言来解决这个问题的方法.还有另一种方法可以做到这一点,我更喜欢(这是我最喜欢的C++技术).如果约束不适合,则可以以忽略函数的方式对函数参数设置约束以进行重载解析.这非常棒,因为您可以将函数重载微调到任意条件.这是如何做:
#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <vector>
template<typename Iter> typename
boost::enable_if<
boost::is_same<typename Iter::value_type,int>,
void>::type
foo(Iter it) { }
int main() {
std::vector<int> v; // this is OK
foo(v.begin());
std::vector<double> v2; // this is an error
foo(v2.begin()); }
Run Code Online (Sandbox Code Playgroud)
如果你编译它,你会得到
b.cc: In function 'int main()':
b.cc:19:16: error: no matching function for call to 'foo(std::vector<double>::iterator)'
Run Code Online (Sandbox Code Playgroud)
这是因为编译器只会考虑foo(),如果它的参数里面有一个value_type类型,那就是'int'(这就是enable_if部分的含义).foo()的第二次调用不能满足这个约束.
在SO中提到了几次enable_if,只需搜索它:https://stackoverflow.com/search?q = enable_if
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |