简体   繁体   English

我应该使用boost :: variant吗?

[英]Should I use boost::variant?

My virtual function can return either a single T or std::vector<T> . 我的虚函数可以返回单个Tstd::vector<T> Is it a good idea to return boost::variant<T, std::vector<T>> in this case or it's better to always return std::vector<T> ? 在这种情况下,返回boost::variant<T, std::vector<T>>是一个好主意吗?还是总是返回std::vector<T>更好? Which looks better and has the least performance overhead? 哪个看起来更好并且性能开销最少? Is it faster to use variant when a single value is returned? 返回单个值时使用variant更快吗?

Performance concerns aside, this depends on the semantics of your function, or more precisely of the return value. 除了性能问题外,这还取决于函数的语义,或更确切地说,取决于返回值。

Do you often need to distinguish (code path wise) between the case where only one T is returned and the multi value case? 您是否经常需要在仅返回一个T的情况和多值情况之间进行区分(代码路径明智)? Or can a simple for(auto t : create_T_orTs()) { ... } do the right thing in either case? 还是简单的for(auto t : create_T_orTs()) { ... }在两种情况下for(auto t : create_T_orTs()) { ... }做对的事情?

My gut feeling is that the former is less likely than the latter, and since variant<> comes with a syntactic 'price' I'd go with KISS and use a std::vector<T> , unless there is a strong semantic reason to distinguish the one and the multiple value cases. 我的直觉是前者的可能性要小于后者,并且由于variant<>带有句法“价格”,因此我会选择使用KISS并使用std::vector<T> ,除非有很强的语义上的原因区分一个和多个价值案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM