今天我遇到了第二个编译器错误,让我感到困惑。对于下面的代码,gcc 抱怨代码具有返回迭代器
完整的代码如下。 注意:只有当使用 gcc 编译时,才会出现此错误。当我使用 clang(
相关问题。这是 forward 的正确使用方法吗?每当您想使用转发引用时,调用
return_iter
的函数返回冲突类型 std::_Rb_tree_iterator<const int*>
和 std::_Rb_tree_const_iterator<const int*>
,但它们都不应该是 const 迭代器,因为 set 不是 const。有人能解释一下为什么在非 const lvalue 上调用 std::end()
方法会返回一个 const_iterator
吗?完整的代码如下。 注意:只有当使用 gcc 编译时,才会出现此错误。当我使用 clang(
Apple LLVM version 8.0.0 (clang-800.0.38)
)编译时,不会出现此错误。我正在使用的 gcc 版本是 g++ (GCC) 5.1.0
。相关问题。这是 forward 的正确使用方法吗?每当您想使用转发引用时,调用
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;
}
< p > LessPtr
在某种程度上是导致此错误的原因。
std::end(std::forward<Container>(container))
。 - T.C.begin
和end
是不适用于rvalue的,如果给定一个rvalue,则它们的行为不正确。 - T.C.