Answer the question
In order to leave comments, you need to log in
How to accept rvalue and lvalue arguments?
Scott Myers' book Effective C++ gives an example of such a function using the universal reference:
template<typename Container, typename Index>
decltype(auto) authAndAccess(Container&& c, Index i) {
return std::forward<Container>(c)[i];
}
decltype(auto) variable = fnt(vector<string>{"one", "two"}, 0);
Answer the question
In order to leave comments, you need to log in
Universal reference allows both types of references to be passed using the reference type inference rules for the template parameter. I already wrote about forward in a comment. There is some difficulty in implementing your Wishlist in one function. Because the type of a container should affect the return type of that container. The easiest option is to write 2 overloads:
template<typename Container, typename Index>
auto authAndAccess(Container&& c, Index i) {
return std::forward<Container>(c)[i];
}
template<typename Container, typename Index>
decltype(auto) authAndAccess(Container& c, Index i) {
return std::forward<Container>(c)[i];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question