我这辈子都无法理解为什么会失败:
#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)
我已经尝试深入研究 boost 代码,但它让我头晕目眩。这似乎很荒谬;如此浪费和不必要。怎么回事?
最佳答案
Boost 试图为您传入的容器制造一组范围,它最终调用 range_detail::is_char_ptr()
,这是一组函数模板的名称,它使用模板参数推导以确定参数是否是某种类型的 char
指针(正如您可能从名称中猜到的那样)。
不幸的是,在匹配非字符指针参数时返回 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;
}
我绝不是复杂模板库实现方面的专家(我使用它们,但我不编写它们),所以我没有声明此更改不会导致其他一些令人讨厌的方面-效果。
关于c++ - 为什么 boost::equals 要求范围是可复制的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8571608/