为什么c++11将get<>(tuple)定义为全局函数而不是tuple的成员?

Why c++11 defines get<>(tuple) as a global function but not a member of tuple?

似乎 std::get 只用在元组 class 上。为什么不让它成为标准库中元组的成员 class,还有其他用途吗?

The reason get is a non-member 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.

source.

get是非成员函数时的片段代码:

template<class T>
void foo ( tuple<T>& t ) {
    get<0>(t) = 10; // get is non-member function
}

和另一个如果get是元组的成员函数:

template<class T>
void foo ( tuple<T>& t ) {
    t. template get<0>() = 10; // ugly
}

您更喜欢 get 哪个版本的用法?对我来说,第一个更好。

还有一个更旧的、不太特定于 c++11 且通常更通用的答案版本。 (如果您只是想知道具体情况,则无需继续阅读)。

一位绝对的 C++ 大师在 this classic DrDobb's article 中描述了自由函数的一般情况。

简短的 n 甜蜜版本:如果您将访问私有成员的 public 接口和仅访问 public 接口的 public 接口分开,您将很难区分class 和 class 上的操作。

它看起来有些丑陋,降低了大多数 IDE 的实用性,但对您的代码模块化有一些深远的影响,尤其是当您接受最近 std 迭代的模板狂潮时。 Matthias 的回答描述了一个明显的例子。

一个更 classic 的优势是,您可以在一个额外的 header 中提供一组免费函数,用户可以根据需要包含这些函数。现在考虑模板化但完全独立的 classes AB 之间的互操作。您现在可以通过提供像 A_B_interop.h 一样的 header 将它们联系在一起,充满免费功能,而无需切换范例。你包括 header,classes 变得更强大。