How do we create functions that return multiple return values ββin C ++? More specifically, if one function returns a tuple, can we combine this function with another that does not explicitly accept tuples? For example, in the code:
#include <tuple>
#include <iostream>
std::tuple <int,int> tuple_ints(int x,int y) {
return std::tuple <int,int> (x,y);
}
int add(int x,int y) {
return x+y;
}
int main() {
std::cout << add(tuple_ints(1,2)) << std::endl;
}
I am trying to compose functions addand tuple_ints. This correctly generates an error:
g++ -std=c++11 test01.cpp -o test01
test01.cpp: In function 'int main()':
test01.cpp:17:37: error: cannot convert 'std::tuple<int, int>' to 'int' for argument '1' to 'int add(int, int)'
std::cout << add(tuple_ints(1,2)) << std::endl;
^
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1
I do not want to change addto accept the tuple; I want the definition to remain basically what it is. Is there anything else we can do so that we can combine these two functions?
Change 1
, N3802. , @Jarod42. , N3802 . , , , ,
#include <tuple>
#include <iostream>
#include <utility>
template <typename F, typename Tuple, size_t... I>
decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) {
return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}
template <typename F, typename Tuple>
decltype(auto) apply(F&& f, Tuple&& t) {
using Indices =
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>;
return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices{});
}
std::tuple <int,int> tuple_ints(int x,int y) {
return std::tuple <int,int> (x,y);
}
int add(int x,int y) {
return x+y;
}
int main() {
std::cout << apply(add,tuple_ints(1,2)) << std::endl;
}
, - ++ 14 , std::index_sequence.