Question

My virtual function can return either a single T or std::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>? Which looks better and has the least performance overhead? Is it faster to use variant when a single value is returned?

Était-ce utile?

La solution

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? Or can a simple for(auto t : create_T_orTs()) { ... } do the right thing in either case?

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top