Function std :: tuple get ()

boost::tuple has a get() member function used as follows:

 tuple<int, string, string> t(5, "foo", "bar"); cout << t.get<1>(); // outputs "foo" 

It seems that C ++ 0x std::tuple does not have this member function, and you should use a non-member form instead:

 std::get<1>(t); 

which to me looks more ugly.

Is there any special reason why std::tuple does not have a member function? Or is this just my implementation (GCC 4.4)?

+44
c ++ boost c ++ 11 tuples
Jul 22 2018-10-22T00:
source share
3 answers

From C ++ 0x draft:

[Note. The reason for get is notmember is that if this function was provided as a member function, code in which a type depending on the template parameter would be required using the template keyword. - final note]

This can be illustrated with this code:

 template <typename T> struct test { T value; template <int ignored> T& member_get () { return value; } }; template <int ignored, typename T> T& free_get (test <T>& x) { return x.value; } template <typename T> void bar () { test <T> x; x.template member_get <0> (); // template is required here free_get <0> (x); }; 
+59
Jul 22 2018-10-22T00:
source share

The existing answers are great and, of course, for the standards committee were vital for this purpose. But there is another problem that, in my opinion, is important enough to mention.

With free features, you have the ability to change the interface without changing the class definition. You can do any type of "gettable" simply by specializing in global get . With the member function, you will need to directly modify the class.

This is one of the reasons why the range-based for built on std::begin/std::end instead of looking for member functions. std::begin/end specialized for array types, so you can use for based on a range with arrays. You can use it with any container, even those that do not have begin/end functions. You can specialize it, for example, for LibXML2 element types, so you can use for based on the xmlElement* range.

You cannot do this if they must be member functions.

In C ++, free functions are the natural interface for many operations that can be performed for different classes.

+23
Oct 16
source share

N3090 / 3092, ยง20.4.2.6 / 8: "Note: the reason get is a function other than that if this function was provided as a member function, code in which the type depended on the template parameter would require the use of template keyword. -end note "

+12
Jul 22 '10 at 21:25
source share



All Articles