2

I'm trying to make a function that returns "vector"

vector<Class A,B or C> _Class123::getVectorList();

or vector<struct A,B or c> _class123::getDataList();

Various classes are three classes that I define. depending on the logic, this function should return one of those.

in C++, is it possible with template?

Manu343726
  • 13,969
  • 4
  • 40
  • 75
dipt
  • 827
  • 9
  • 14

1 Answers1

3

You sound like you want a discriminated union, in which case you might want to look into something like Boost.Variant:

http://www.boost.org/doc/libs/1_54_0/doc/html/variant.html

Your function would then be:

std::vector<boost::variant<A,B,C> > _Class123::getVectorList();
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
  • Just for curiosity: Is there a [tag:c++11] standard solution for this problem? – πάντα ῥεῖ Nov 17 '13 at 15:49
  • Thank you, but I couldn't use other lib. Is there any other way without ext.lib? – dipt Nov 17 '13 at 15:50
  • 3
    @user1060039: The other way is to write your own discriminated union. There's no standard type for that. But there's no sensible reason not to use this Boost library; it's header-only, with an unrestrictive license. – Mike Seymour Nov 17 '13 at 15:58
  • 1
    If you're not allowed to use boost', simply implement the variant data type yourself, this has gotten a lot easier in C++11 due to the relaxation of union. – Skeen Nov 17 '13 at 16:03
  • @g-makulik: No, there's no equivalent of Boost.Variant in the C++ Standard Library unfortunately (yet, at least). – Stuart Golodetz Nov 17 '13 at 16:16