boost::tuple
有一个 get()
成员函数,使用如下:
tuple<int, string, string> t(5, "foo", "bar");
cout << t.get<1>(); // outputs "foo"
看来C++0x std::tuple
没有这个成员函数,只能改用非成员函数形式:
std::get<1>(t);
在我看来更丑。
std::tuple
没有成员函数有什么特别的原因吗?还是只是我的实现(GCC 4.4)?
最佳答案
来自 C++0x 草案:
[ Note: The reason get is a nonmember function is that if this functionality had been provided as a member function, code where the type depended on a template parameter would have required using the template keyword. — end note ]
这可以用这段代码来说明:
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);
};
https://stackoverflow.com/questions/3313479/