gpt4 book ai didi

c++ - 没有为 boost::tuples 定义 ==

转载 作者:行者123 更新时间:2023-11-30 03:42:05 25 4
gpt4 key购买 nike

我有这个代码:

...
#include "boost/tuple/tuple_comparison.hpp"
...
template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(const Args && ... args)
{
using noRef = boost::tuple<typename std::remove_reference<Args>::type...>;
static map<noRef, ReturnType, less<>> cache;
auto key = std::tie(noRef{ boost::make_tuple(args ...) });
auto it = cache.lower_bound(key);
ReturnType result;
if (it->first == key) { ...

但是当我尝试编译它时,我收到了这个错误:

error C2678: binary '==': no operator found which takes a left-hand operand of type 'const noRef' (or there is no acceptable conversion)

为什么会发生这种情况,因为 noRefboost::tuple 的别名,而 tuple_comparison 应该处理这种情况?

发现错误,不知道如何解决:

看来错误是在std::tie操作中。所以重写为:

    auto key = noRef{ boost::make_tuple(args ...) };

工作正常。问题在于此解决方案效率低下,因为 key 是整个元组的潜在昂贵拷贝,而使用 tie 是引用元组(小得多)。那么,我怎样才能引用 it->first 元组呢?我应该使用相同的 tie 技巧吗?

最佳答案

这一行编译的唯一原因是 MSVC 的 Evil ExtensionTM,它允许非 const 左值引用绑定(bind)到临时对象:

auto key = std::tie(noRef{ boost::make_tuple(args ...) });

这应该只是

auto key = boost::tie(args...);

它创建一个 boost::tuple 引用以供稍后查找。

此外,如评论中所述,if 检查应先验证 it != cache.end(),然后再尝试取消引用它(谢谢!)。

最后,const Args && ... 没有多大意义,因为人们不太可能想要接受 const 右值。它可能应该是 const Args&...Args&&...

关于c++ - 没有为 boost::tuples 定义 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com