Cur*_*ous 4 c++ gcc const-iterator auto c++11
这是今天的第二个编译错误让我感到困惑.不知何故,对于下面的代码,gcc抱怨代码具有返回迭代器return_iter返回冲突类型的函数std::_Rb_tree_iterator<const int*>然后std::_Rb_tree_const_iterator<const int*>,但是它们都不应该是const迭代器,因为set不是const.任何人都可以解释为什么在std::end()非const lvalue上调用该方法会返回一个const_iterator?
完整的代码粘贴在下面.
注意我只在编译时遇到此错误gcc.当我用clang编译它时,这个错误没有出现(Apple LLVM version 8.0.0 (clang-800.0.38).我正在使用的gcc版本是g++ (GCC) 5.1.0
一个相关的问题.这是正确使用前进吗?std::forward每当您想使用转发参考时,是否可以打电话?我在下面调用它的原因是为了防止类型在对象是rvalue时重载某些方法.
#include <vector>
#include <string>
#include <set>
#include <iostream>
using namespace std;
int global_value = 1;
class LessPtr {
public:
template <typename PointerComparableOne, typename PointerComparableTwo>
constexpr auto operator()(PointerComparableOne&& lhs,
PointerComparableTwo&& rhs) const {
return *std::forward<PointerComparableOne>(lhs) <
*std::forward<PointerComparableTwo>(rhs);
}
using is_transparent = std::less<void>::is_transparent;
};
template <typename Container, typename Key>
auto return_iter(Container&& container, Key&& key) {
if (global_value == 1) {
return std::forward<Container>(container).lower_bound(std::forward<Key>(key));
}
else {
return std::end(std::forward<Container>(container));
}
}
void do_stuff(std::set<const int*, LessPtr>& set_ptrs) {
// auto value = string{"something"};
auto value = 1;
auto iter = return_iter(set_ptrs, &value);
cout << reinterpret_cast<void*>(&iter) << endl;
}
int main() {
std::set<const int*, LessPtr> set_ptrs;
do_stuff(set_ptrs);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在LessPtr以某种方式需要导致此错误..
这是std::set处理透明比较器的方式中的libstdc ++错误.这是一个较短的例子:
int main() {
using S = std::set<const int*, LessPtr>;
S set_ptrs;
int i = 0;
const int ci = 0;
static_assert(std::is_same<
decltype(set_ptrs.lower_bound(&ci)), S::iterator>{}, "!"); // OK
static_assert(std::is_same<
decltype(set_ptrs.lower_bound(&i)), S::iterator>{}, "!"); // Error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一个断言很好,我们称之为lower_bound(Key const&),返回一个iterator.第二个断言触发因为我们正在调用函数模板template <class K> lower_bound(K const&),因为它LessPtr是透明的,并且该重载是一个更好的匹配(因为它是一个完全匹配),而对于libstdc ++,它正在返回一个const_iterator.
但是,set_ptrs是不是const,所以它不应该是.我提交了78134
| 归档时间: |
|
| 查看次数: |
225 次 |
| 最近记录: |