/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <iostream>
#include <type_traits>
#include <utility>
namespace matlab
{
template <typename...> class tuple;
template <> class tuple<> {};
template <typename T, typename...U>
class tuple<T, U...>
{
public:
tuple() = default;
template <typename X, typename...Y>
tuple(X&& x, Y&&...y)
: head_(std::forward<X>(x))
, tail_(std::forward<Y>(y)...) { }
template <typename X, typename...Y>
tuple& operator = (const tuple<X, Y...>& t)
{
head_ = T(t.head_);
tail_ = t.tail_;
return *this;
}
private:
template <typename...> friend class tuple;
T head_;
tuple<U...> tail_;
};
template <typename...T>
tuple<T...> make_tuple(const T&...t) {
return {t...};
}
template <typename...T>
tuple<T&...> tie(T&...t) {
return {t...};
}
namespace instant_tests
{
char ch = 0;
int ii = 123;
float ff = 2.7;
static_assert(
std::is_same<
tuple<char, int, float>,
decltype(make_tuple(ch, ii, ff))>::value,
"fails"
);
}
}
using matlab::tuple;
using matlab::make_tuple;
using matlab::tie;
tuple<int, float> foo(int a, float b)
{
return {a * a, b * b};
}
float bar(int a, float b)
{
int aa = {};
float bb = {};
tie(aa, bb) = foo(a, b);//decompose results
return aa + bb;
}
int main()
{
using std::cout;
using std::endl;
int i0 = 123, i1 = 42;
float f0 = 2.7, f1 = 3.14;
cout << "Before" << endl;
cout << "i0: " << i0 << endl;
cout << "f0: " << f0 << endl;
cout << "i1: " << i1 << endl;
cout << "f1: " << f1 << endl << endl;
tie(i0, f0) = make_tuple(i1, f1);
cout << "After" << endl;
cout << "i0: " << i0 << endl;
cout << "f0: " << f0 << endl;
cout << "i1: " << i1 << endl;
cout << "f1: " << f1 << endl << endl << endl;
i0 = 123;
cout << "Before exchange" << endl;
cout << "i0: " << i0 << endl;
cout << "i1: " << i1 << endl << endl;
tie(i0, i1) = make_tuple(i1, i0);//exchange values python style
cout << "After exchange" << endl;
cout << "i0: " << i0 << endl;
cout << "i1: " << i1 << endl << endl;
auto r = bar(2, 3);
cout << "After bar" << endl;
cout << "r: " << r << endl << endl;
tie(i0, i1) = make_tuple(1, 2);
cout << "After assign to literals" << endl;
cout << "i0: " << i0 << endl;
cout << "i1: " << i1 << endl << endl;
const int x = 2;
const int y = 3;
tie(i0, i1) = make_tuple(x, y);
cout << "After assign to constants" << endl;
cout << "i0: " << i0 << endl;
cout << "i1: " << i1 << endl;
}