c++ - 引用包装器的初始化列表

标签 c++ c++11

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

#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 class),我倾向于第二种选择。但是,我觉得它很冗长,我很少在其他代码中看到它。有什么充分的理由让我更喜欢其中一种选择吗?

最佳答案

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

→ 始终使用 reference_wrapper<T>T*什么时候nullptr应该无效。

如果它真的太冗长了,你总是可以用更短的名字定义一个类型别名:

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_;

还有 gsl::not_null<T*> Guidelines Support Library 中的类.有关相关问答,请参阅 gsl::not_null<T*> vs. std::reference_wrapper<T> vs. T& .

关于c++ - 引用包装器的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985913/

相关文章:

支持所有 C++11 并发功能的 C++ 编译器?

c++ - 必须在 std::vector<std::thread> 中加入 std::thread 两次以避免从线程 dtor 终止

c++ - 文本文件末尾的项目被读取两次

c++ - c/c++ 中的可逆浮点排序

c++ - asn1c 不会从 asn.1 模块中提取 OCTET STRING 的默认值

c++ - 不使用 std::function 将捕获的 lambda 转换为函数指针

c++ - 停止 C++ 11 std::threads 等待 std::condition_variable

c++ - 为 Vim 调整 C++ IDE 插件

c++ - 为什么将变量标记为常量?

c++ - 如何将可变数量的值读入 std::tuple?