我经常遇到需要存储非拥有指针列表或对基类对象的引用的情况。当然,我可以做
#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
类的实例)不能没有其他对象(Base
或 Derived
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/