在 std::array 上使用 std::get 会带来更好的性能吗?
Does using std::get on std::array give better performance?
标准库class模板std::array<T, N>
同时具有成员访问器函数
constexpr const T& operator[]( size_type n ) const;
以及非成员访问函数模板
template< size_t I, class T, size_t N >
constexpr const T& get( const array<T,N>& a ) noexcept
在 C++17 中,所有 operator[]
重载都已完成 constexpr
,所以我想知道 std::get
的剩余优势是什么(如果有的话)。例如。在这样的程序中:
int main()
{
auto a = std::array<int, 3> { 1, 2, 3 };
constexpr auto idx = 0;
std::cout << a[idx] << '\n';
std::cout << std::get<idx>(a) << '\n';
}
任何体面的编译器都应该能够为 operator[]
和 get
传播常量索引值 0
。
问题:std::get
对std::array
有什么好处而operator[]
没有?
结构化绑定需要 Get。
其他通用元组代码也将使用它。
Question: what benefits does std::get
on std::array
give that operator[]
doesn't?
除了提供与元组的通用接口(这显然是我们在 C++ 中隐式一般定义产品类型的方式)之外,std::get
确实还有一个优势。编译时边界检查:
std::array<int, 3> arr;
arr[4] = 17; // bad
std::get<5>(arr) = 42; // bad, but also compile error, so actually good
那是因为如果索引超出范围(请参阅 [array.tuple]),元组接口显然是格式错误的,但是 operator[]
只是您必须追踪的运行时问题。
标准库class模板std::array<T, N>
同时具有成员访问器函数
constexpr const T& operator[]( size_type n ) const;
以及非成员访问函数模板
template< size_t I, class T, size_t N >
constexpr const T& get( const array<T,N>& a ) noexcept
在 C++17 中,所有 operator[]
重载都已完成 constexpr
,所以我想知道 std::get
的剩余优势是什么(如果有的话)。例如。在这样的程序中:
int main()
{
auto a = std::array<int, 3> { 1, 2, 3 };
constexpr auto idx = 0;
std::cout << a[idx] << '\n';
std::cout << std::get<idx>(a) << '\n';
}
任何体面的编译器都应该能够为 operator[]
和 get
传播常量索引值 0
。
问题:std::get
对std::array
有什么好处而operator[]
没有?
结构化绑定需要 Get。
其他通用元组代码也将使用它。
Question: what benefits does
std::get
onstd::array
give thatoperator[]
doesn't?
除了提供与元组的通用接口(这显然是我们在 C++ 中隐式一般定义产品类型的方式)之外,std::get
确实还有一个优势。编译时边界检查:
std::array<int, 3> arr;
arr[4] = 17; // bad
std::get<5>(arr) = 42; // bad, but also compile error, so actually good
那是因为如果索引超出范围(请参阅 [array.tuple]),元组接口显然是格式错误的,但是 operator[]
只是您必须追踪的运行时问题。