【问题标题】:Initializer list of reference wrappers引用包装器的初始化列表
【发布时间】:2015-11-29 17:46:41
【问题描述】:

我经常遇到需要存储非拥有指针列表或对基类对象的引用的情况。当然可以了

#include <initializer_list>
#include <list>

class Base {};

class Derived {};

class Container {
public:
    void setObjects(const std::initializer_list<const Base *> objects); // Set objects_ member
private:
    std::list<const Base *> objects_; // Should store Base and Derived objects
};

使用std::reference_wrapper,我也可以使用

#include <initializer_list>
#include <list>
#include <functional> // for std::reference_wrapper

class Base {};

class Derived {};

class Container {
public:
    void setObjects(const std::initializer_list<std::reference_wrapper<const Base> > objects); // Set objects_ member
private:
    std::list<std::reference_wrapper<const Base> > objects_; // Should store Base and Derived objects
};

当我想表达一个对象(在我的例子中是 Container 类的实例)如果没有其他对象(BaseDerived 类的实例)就不能存在的事实时,我倾向于更喜欢第二种选择。但是,它对我来说感觉很冗长,而且我很少在其他代码中看到它。有什么好的理由让我更喜欢一种选择吗?

【问题讨论】:

  • 第二种方法无效:std::reference_wrapper&lt;anything &amp;&gt; 无效。你可能是指std::reference_wrapper&lt;const Base&gt;,没有&amp;
  • 是的,对不起。我将编辑我的问题。

标签: c++ c++11


【解决方案1】:

我认为正确性比避免冗长更重要。至少对于严肃的项目。

→ 当nullptr 无效时,始终使用reference_wrapper&lt;T&gt; 而不是T*

如果它真的过于冗长,你总是可以定义一个名称更短的类型别名:

template<typename type> using ref = std::reference_wrapper<type>;

std::list<ref<const int>> objects_;

或者只是一个“标签”帮助类型来记录意图:

template<typename type> using not_null = type;

std::list<not_null<const int*>> objects_;

Guidelines Support Library 中还有 gsl::not_null&lt;T*&gt; 类。相关问答请见gsl::not_null<T*> vs. std::reference_wrapper<T> vs. T&

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多