为什么 boost::equals 要求范围可复制?

发布于 2024-12-21 20:03:54 字数 592 浏览 5 评论 0原文

我一生都无法理解为什么会失败:

#include <vector>

#include "boost/algorithm/string/predicate.hpp"

struct Test
:
    public std::vector<int>
{
    Test() { }
    Test(const Test&) { assert(false); }
};

int main()
{
    Test a;
    Test b;
    boost::algorithm::equals(a, b);

    return 0;
}

输出:

$ g++ boostEqualsCopyDemo.cpp -I /usr/include/boost-1_47
$ a.out
a.out: boostEqualsCopyDemo.cpp:10: Test::Test(const Test&): Assertion `false' failed.
Aborted (core dumped)

我已经尝试挖掘升压代码,但这让我头晕。这似乎很荒唐;如此浪费且不必要。这是怎么回事?

Can't for the life of me understand why this fails:

#include <vector>

#include "boost/algorithm/string/predicate.hpp"

struct Test
:
    public std::vector<int>
{
    Test() { }
    Test(const Test&) { assert(false); }
};

int main()
{
    Test a;
    Test b;
    boost::algorithm::equals(a, b);

    return 0;
}

Output:

$ g++ boostEqualsCopyDemo.cpp -I /usr/include/boost-1_47
$ a.out
a.out: boostEqualsCopyDemo.cpp:10: Test::Test(const Test&): Assertion `false' failed.
Aborted (core dumped)

I've tried digging through the boost code but it's making my head spin. It seems absurd; so wasteful and unnecessary. What's going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不回头走下去 2024-12-28 20:03:54

Boost 尝试为传入的容器创建一组范围,最终调用 range_detail::is_char_ptr(),这是一组使用模板参数推导的函数模板的名称确定参数是否是某种 char 指针(正如您可能通过名称猜到的那样)。

不幸的是,当匹配非字符指针参数时,“catch-all”函数模板会返回 0 并按值获取其参数。

我认为可以通过更改参数以采用 const& 来解决此问题。在文件 boost/range/as_literal.hpp 中查找:

    template< class T >
    inline long is_char_ptr( T /* r */ )
    {
        return 0L;
    }

并将其更改为:

    template< class T >
    inline long is_char_ptr( T const& /* r */ )  // <-- add const&
    {
        return 0L;
    }

我绝不是复杂模板库实现方面的专家(我使用它们,我不使用它们)写下它们),所以我不声称此更改不会导致其他一些令人讨厌的副作用。

Boost is trying to manufacture a set of ranges for the containers you pass in, and it ends up calling range_detail::is_char_ptr(), which is the name of a set of function templates that uses template parameter deduction to determine if the parameter is a char pointer of some sort or not (as you might guess by the name).

Unfortunately, the 'catch-all' function template that returns 0 when matching non-char-pointer parameters takes its parameter by value.

I think this can be fixed by changing the parameter to take a const& instead. Look in the file boost/range/as_literal.hpp for:

    template< class T >
    inline long is_char_ptr( T /* r */ )
    {
        return 0L;
    }

and change it to:

    template< class T >
    inline long is_char_ptr( T const& /* r */ )  // <-- add const&
    {
        return 0L;
    }

I'm by no means an expert in the implementation of complex template libraries (I use 'em, I don't write 'em), so I make no claims that this change won't cause some other nasty side-effect.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文