tuple其实就是泛化版的pair,对于C++11,tuple的使用及例程如下:
C++11不支持简单的遍历tuple,C++17可以使用std::apply遍历tuple;
#include <iostream>
#include <memory>
#include <algorithm>
#include <string>
#include <functional>
#include <tuple>
#include <vector>
using namespace std;
void func(int x, int y)
{
cout << x << y << endl;
}
auto ll = [](int x, int y) {
cout << "lambda" << endl;
};
class C
{
public:
void operator()(int x, int y) const;
void memfunc(int x, int y) const;
};
class tupt
{
public:
tupt() = default;
virtual ~tupt() = default;
tupt(int a, int b, int c, std::string d):a(a),b(b),c(c),d(d) {}
int getAvalue()
{
return a;
}
protected:
int a;
int b;
int c;
std::string d;
};
enum class TYPE
{
TYPE_1,
TYPE_2,
TYPE_3,
TYPE_4
};
std::tuple<int, int, double, std::string> tup{};
std::tuple<int, int, double, std::string>& getTuple(TYPE typ)
{
switch (typ)
{
case TYPE::TYPE_1:
tup = std::make_tuple<int, int, double, std::string>(1,1,1.45, "TYPE1");
break;
case TYPE::TYPE_2:
tup = std::make_tuple<int, int, double, std::string>(2,2,2.12,"TYPE2");
break;
default:
tup = std::make_tuple<int, int, double, std::string>(0,0,0.0,"TYPE3");
break;
}
return tup;
}
void print(const char * format, ...)
{
}
int main()
{
C c{};
std::shared_ptr<C> sp(new C);
std::bind(func, 77, 33)();
std::tuple<int, int, std::string, double> t1{ 1, 2, "testtuple", 2.3 };
cout << std::get<0>(t1) << endl;
std::string s{};
tuple<string&> t(s);
get<0>(t) = "hello";
cout << s << endl;
make_tuple(std::ref(s));
std::vector<std::tuple<int, float>> v{ {1, 1.2}, {2, 2.3} };
for (auto item : v)
{
cout << std::get<0>(item) << endl;
cout << std::get<1>(item) << endl;
}
auto testtup = getTuple(TYPE::TYPE_1);
std::tuple_cat(v.at(0), v.at(1));
std::tuple<int, char, double, TYPE> mytuple(10,'a',3.22, TYPE::TYPE_1);
//get tuple element number
auto size_of_tuple = std::tuple_size<decltype(mytuple)>::value;
int a{};
char b{};
double d{};
TYPE type{};
std::tie(a, b, d, type) = mytuple;
cout << a << endl << b << endl << d << endl << static_cast<int>(type) << endl;
std::tuple<int, double, tupt> my(1, 2.3, {1,2,3,"test"});
cout << std::get<2>(my).getAvalue() << endl;
int mya = 0;
decltype(std::get<0>(my)) sss = mya;
if (typeid(sss) == typeid(int))
{
cout << "same type " << endl;
}
std::tuple<std::string, int, double> mytie{"mytie", 1, 2.2};
std::string myt{"mytiefortest"};
int mytiea = 2;
double mytieb = 2.54;
cout << std::get<0>(mytie) << endl;
std::tie(myt, mytiea, mytieb) = mytie;
cout << myt << endl;
return 0;
}