I'm reading Scott Meyers's Effective Modern C++ and I'm trying on my machine the example he provides for the Deducing Types chapter.
He provides this function:
template <typename Container, typename Index>
auto decltype_test_1(Container& c, Index i) -> decltype(c[i])
{
return c[i];
}
And then it uses the function in this way:
std::deque<int> d;
…
decltype_test_1(d, 5) = 10; // authenticate user, return d[5],
// then assign 10 to it;
// this won't compile!
Saying that it won't compile. I tried with MSVC and it does compile. I wrote the following in the main
:
std::deque<int> d;
d.push_back(0);
d.push_back(1);
d.push_back(2);
decltype_test_1(d, 0) = 10;
for each (auto item in d)
cout << item << endl;
I don't understand why it compiles and, most of all, it shows 10
as the first element of the deque. For what he explains this code is wrong. Why does it work here? What am I missing?
That comment is not about the C++11 example with the trailing decltype, it's about the C++14 version with auto
type deduction:
template <typename Container, typename Index>
auto decltype_test_1(Container& c, Index i) //no trailing return
{
return c[i];
}
Using this version, the example will fail to compile, because the type will be deduced as a value rather than a reference, so you can't directly assign to the result of a call to the function.
As is indicated on the next page of the book, the way to get the correct type deduced without a trailing return type is to use decltype(auto)
instead of auto
.
template <typename Container, typename Index>
decltype(auto) decltype_test_1(Container& c, Index i)
{
return c[i];
}