STL-pair-like triplet class - do I roll my own?

点点圈 提交于 2019-11-30 17:03:09
Joseph Mansfield

No, don't roll your own. Instead, take a look at std::tuple - it's a generalization of std::pair. So here's a value-initialized triple of ints:

std::tuple<int, int, int> triple;

If you want, you can have a type alias for triples only:

template<typename T1, typename T2, typename T3>
using triple = std::tuple<T1, T2, T3>;

If you can use C++11, use std::tuple

If not, use boost::tuple

John Dibling

If you're using C++11, you can use std::tuple.

If you're using C++03, then you'll either need to resort to rolling your own (which isn't too hard), or using tuple from Boost.

I think you need something like this:

template<typename T>
struct triplet
{
    T first, middle, last;
};

template<typename T>
triplet<T> make_triplet(const T &m1, const T &m2, const T &m3) 
{
    triplet<T> ans;
    ans.first = m1;
    ans.middle = m2;
    ans.last = m3;
    return ans;
}

Examples of usage:

triplet<double> aaa;
aaa = make_triplet<double>(1.,2.,3.);
cout << aaa.first << " " << aaa.middle << " "  << aaa.last << endl;

triplet<bool> bbb = make_triplet<bool>(false,true,false);
cout << bbb.first << " " << bbb.middle << " "  << bbb.last << endl;

I'm using this and it is enough for my purposes... If you want different types, though, just do some modifications:

template<typename T1, typename T2, typename T3>
struct triplet
{
    T1 first; 
    T2 middle;
    T3 last;
};

template<typename T1, typename T2, typename T3>
triplet<T1,T2,T3> make_triplet(const T1 &m1, const T2 &m2, const T3 &m3) 
{
    triplet<T1,T2,T3> ans;
    ans.first = m1;
    ans.middle = m2;
    ans.last = m3;
    return ans;
}

And the usage will be very similar:

triplet<bool,string,myDouble> ccc;
ccc = make_triplet<bool,string,double>(false,"AB",3.1415);
ccc.middle = "PI";
cout << ccc.first << " " << ccc.middle << " "  << ccc.last << endl;

To add the aspect of similarity to std::pair, you could define a class that has first, second and third. My guess is that in In that case you cannot avoid making a subclass of std::pair and add a 'third' member. It's a few lines of code.

Furthermore, if you often use these things with the same type, you could make twins and triplet classes as well. Easily made with C++-11's 'using', like:

template <typename T> using twins = std::pair<T,T>;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!