Мне нужна помощь, чтобы понять, почему возвращаемый тип updateElementUsingTemplate отличается от updateElementUsingAuto приведенным ниже кодом.
#include <iostream>
#include <array>
#include <vector>
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
template<typename Container, typename Index>
decltype(auto) updateElementUsingTemplate(Container&& container, Index index)
{
std::cout << "Template Return Type : "<<
type_id_with_cvr<decltype( container[index] )>().pretty_name() << '\n';
return container[index];
}
decltype(auto) updateElementUsingAuto(auto&& container, size_t index)
{
std::cout << "Auto Return Type : "<<
type_id_with_cvr<decltype( container[index] )>().pretty_name() << '\n';
return container[index];
}
int main() {
std::array<int,2> arr= {1,2};
updateElementUsingTemplate( arr, 1 ) = 12;
updateElementUsingAuto( arr, 1 );// = 12;
//Generates compiler error if uncommented: lvalue required as left operand of assignment.
//Why is type being returned "int" in above statement?
std::cout << "Auto Returned Type : "<<
type_id_with_cvr<decltype( updateElementUsingAuto(arr,1) )>().pretty_name() << '\n';
std::cout << "Template Returned Type : "<<
type_id_with_cvr<decltype( updateElementUsingTemplate(arr,1) )>().pretty_name() << '\n';
return 0;
}
Фактический результат:
Тип возврата шаблона: int &
Тип автоматического возврата: int &
Тип автоматического возврата: int
Возвращаемый шаблон Тип: int &
Ожидаемый результат:
Тип возвращаемого шаблона: int &
Тип автоматического возврата: int &
Тип авто возвращено: int &
Возвращаемый шаблон Тип: int &
Я ожидал, что updateElementUsingAuto и updateElementUsingTemplate будут возвращать int &, где в качестве фактических результатов возвращаются int и int & соответственно.
Почему существует разница в типе возврата обеих функций?
Ваша помощь будет высоко оценена.
Редактировать 1: Как уже упоминалось @cpplearner, эта проблема, похоже, ошибка gcc.
Если кто-то все еще хочет использовать синтаксис, вы можете сделать это, используя синтаксис завершающего типа:
decltype (auto) updateElementUsingAuto (auto && container, size_t index) -> decltype (container [index]) {...}