template <typename T>
const T& longestOfTheThree(const T& a, const T& b, const T& c){
T longest = a;
if (longest.length < b.length){longest = b;}
if (longest.length < c.length){longest = c;}
return longest;
}
Can someone explain why const T&
(specifically the &
before longestOfTheThree
) is invalid? Why does the code only compile if I remove the &
?
This code compiles:
template <typename T>
const T longestOfTheThree(const T& a, const T& b, const T& c){
T longest = a;
if (longest.length < b.length){longest = b;}
if (longest.length < c.length){longest = c;}
return longest;
}
You are returning a reference to an ASDV ("stack" variable). That doesn't work: longest
is destructed before return.
If you'd like to return a reference, you can do, for example:
template <typename T>
const T& longestOfTheThree(const T& a, const T& b, const T& c){
if (longest.length < b.length) { return b; }
if (longest.length < c.length) { return c; }
return a;
}
Or, if you'd like to keep longest
, you can have a pointer:
template <typename T>
const T& longestOfTheThree(const T& a, const T& b, const T& c){
const T* longest = &a;
if (longest->length < b.length) { longest = &b; }
if (longest->length < c.length) { longest = &c; }
return *longest;
}
Not sure why you try to implement your own template when there is std::max
that will do almost what you need, but if you want to hide using of longest
member I would do something like:
template<class T>
const T& longestOf(std::initializer_list<T> ilist)
{
return *std::max_element(ilist.begin(), ilist.end(), [](const T& a, const T& b) {return a.longest < b.longest;});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.