如何使用boost::adaptors:: transforms从模板化的类和向量生成范围?

How do I use boost::adaptors::transformed to produce a range from a templated class and a vector?

本文关键字:向量 范围 adaptors boost 何使用 transforms      更新时间:2023-10-16

我问了一个关于使用lambda来实现类似的东西的问题,但是不能得到这个工作,所以我尝试使用函子来解决问题。无论如何,这可能更简洁,因为它不涉及构造std::function对象,并且更接近文档中列出的示例。

下面是一个简单的设置,说明了我的问题:

#include <boost/range/adaptor/transformed.hpp>
#include <vector>
// some structure
template <typename T>
struct MyStruct
{
    MyStruct(T t)
    {
    }
};
template <typename T>
struct Converter
{
    using return_type = MyStruct<T>;
    return_type operator()(const T& value)
    {
        return return_type(value);
    }
};
int main(int argc, const char* argv[])
{
    std::vector<int> vec {1, 2, 3};
    auto val = vec | boost::adaptors::transformed(Converter<int>());
    return 0;
}

当我尝试编译这个时,我得到以下错误消息:

/home/user/packages/boost/mpl/eval_if.hpp:38:31: error: no type named .hpp' type ' in ' boost::mpl::eval_if<boost::is_same<boost::use_default, boost::use_default>, boost::result_of<const Converter<int>(int&)>, boost::mpl::identity<boost::use_default> >::f_ {aka struct boost::result_of<const Converter<int>(int&)>} '

我不知道这是怎么回事。我无法发现代码中的任何错误。什么好主意吗?

错误告诉您boost::result_of<const Converter<int>(int&)>没有type成员。换句话说,当使用const Converter<int>对象时,函数调用操作符不起作用。一旦您知道了问题所在,就很容易发现问题所在:

return_type operator()(const T& value) const
//                                     ^^^^^
{
    return return_type(value);
}