【问题标题】:boost::enable_if enabler() related to the tutorial on creating an iterator with boost::iterator_facadeboost::enable_if enabler() 与使用 boost::iterator_facade 创建迭代器的教程相关
【发布时间】:2021-06-08 20:58:16
【问题描述】:

所以...看看这段代码:

    #include <boost/iterator/iterator_facade.hpp>
    #include <boost/type_traits/is_convertible.hpp>
    #include <boost/utility/enable_if.hpp>
    
    template <class Value>
    class LMI
      : public boost::iterator_facade<LMI<Value>, Value, boost::forward_traversal_tag>
    {
    private:
      int xsize, ysize, x, y;
      Level *level {0};             // iterator invalid if level == 0

    public:
      LMI(LMI<OtherValue> const &L, 
          typename boost::enable_if<boost::is_convertible<OtherValue*,Value*>,
                                    enabler>::type = enabler())
        : xsize {L.xsize}, ysize {L.ysize}, x {L.x}, y {L.y}, level {L.level}
      {};
    };

编译器抱怨没有标识符'enabler' ...这一切都来自https://www.boost.org/doc/libs/1_72_0/libs/iterator/doc/iterator_facade.html#telling-the-truth的boost示例文档

我现在意识到 enable_if 和 is_convertible 是确定是否创建此转换构造函数的魔术模板(本教程也说过),但我没有看到有关此“启用器() " 函数 --- 这个用法是教程不正确吗?自编写教程以来,用法是否发生了变化?

这可能有助于读者了解这个模板是这样使用的:

typedef LMI<Tile> Level_Map_Iterator;
typedef LMI<Tile const> cLevel_Map_Iterator;

...关键是在创建 LMI 时它会创建转换构造函数,而在创建 LMI 时它不会。

【问题讨论】:

  • 嗯...enabler 的定义在该示例中直接给出。你看到struct enabler {};这行了吗?用示例进行实验很好,但请记住,如果您的实验无法编译,请首先查看您删除的示例部分。
  • 现在我觉得自己很笨。谢谢。

标签: c++ boost


【解决方案1】:

所以...不好意思,如果我添加的话

struct enabler {};

到类模板的私有部分,一切都好。不能完全解释这是如何工作的——但我现在对秘方很满意。显然,我正在根据自己的工作调整教程示例,叹气。

【讨论】:

  • 您可以更改问题以询问它为什么/如何工作... ;) 解释并不深入,但模板的语法可能会令人困惑。 (如果您想自己考虑一下:enabler 的特殊之处在于它无法匹配从您的班级之外提供的任何类型。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
相关资源
最近更新 更多