gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:01:09 25 4
gpt4 key购买 nike

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);
};

关于c++ - std::tuple get() 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com