c++ - std::tuple get() 成员函数

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/

相关文章:

c++ - 为什么 C/C+ +'s "#pragma once"不是 ISO 标准?

c++ - 内存分配是系统调用吗?

c++ - queue::push 后双重释放或损坏

c++ - 是否有可以解析 C++ 的优秀 Python 库?

c++ - 为什么优化会杀死这个功能?

c++ - 在 std::map 中更改元素键的最快方法是什么

c++ - 使用 Qt 进行序列化

c++ - 每个类都应该有一个虚拟析构函数吗?

>' should be ` > >' within ">c++ - 模板内的模板 : why "` >>' should be ` > >' within

c++ - 如何在 GCC 搜索路径中包含头文件?