gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:14:21 24 4
gpt4 key购买 nike

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

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com