我经常遇到需要存储非拥有指针列表或对基类对象的引用的情况。当然,我可以做到
#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
类的实例)时不能存在的事实,我倾向于选择第二种选择。但是,我感觉很啰嗦,我很少在其他代码中看到它。有什么理由我宁愿选择另一种替代方案吗?
答案 0 :(得分:0)
我认为正确性比避免冗长更重要。至少对于严肃的项目。
→当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&。