C++11新特性新特性std::tuple的使用方法的使用方法
1. 引入头文件引入头文件
#include <tuple>
2. std::tuple初始化初始化
std::tuple<int, std::string, float> t1(10, "Test", 3.14);
这里要注意,不是所有的C++ 11编译器都支持copy-list-initialization的方式。如下代码所示。
std::tuple<int, int> foo_tuple()
{
return {1, -1}; // Error until N4387
return std::tuple<int, int>{1, -1}; // Always works
return std::make_tuple(1, -1); // Always works
}
3. 打印打印std::tuple
打印std::tuple可以将它的元素逐个打印出来,不过非常繁琐,我们可以通过如下通用的打印函数,帮助我们一次性的将tuple
的所有要素打印出来。
#include <iostream>
#include <tuple>
#include <string>
// helper function to print a tuple of any size
template<class Tuple, std::size_t N>
struct TuplePrinter {
static void print(const Tuple& t)
{
TuplePrinter<Tuple, N-1>::print(t);
std::cout << ", " << std::get<N-1>(t);
}
};
template<class Tuple>
struct TuplePrinter<Tuple, 1> {
static void print(const Tuple& t)
{
std::cout << std::get<0>(t);
}
};
template<typename... Args, std::enable_if_t<sizeof...(Args) == 0, int> = 0>
void print(const std::tuple<Args...>& t)
{
std::cout << "()";
}
template<typename... Args, std::enable_if_t<sizeof...(Args) != 0, int> = 0>
void print(const std::tuple<Args...>& t)
{
std::cout << "(";
TuplePrinter<decltype(t), sizeof...(Args)>::print(t);
std::cout << ")";
}
// end helper function
int main()
{
std::tuple<int, std::string, float> t1(10, "Test", 3.14);
print(t1);
}
输出:
评论0