Re: tuples in C++11
On 8/14/2012 2:17 PM, Single Stage to Orbit wrote:
Hello!
Suppose I have the following:
int main()
{
typedef boost::tuple<int, int, int> tuple3;
std::vector<tuple3> tuples;
tuples.push_back(tuple3(1, 2, 3));
tuples.push_back(tuple3(7, 8, 9));
tuples.push_back(tuple3(4, 5, 6));
for (auto& i : tuples)
std::cout << i.get<0>() << " " << i.get<1>() << " " <<
i.get<2>() << '\n';
return 0;
}
Is it even possible to have something like this:
for (auto& i : tuples)
{
for (unsigned j = 0; j < 3; ++j)
{
std::cout << i.get<j>();
if (j < 3)
std::cout << " ";
}
std::cout << '\n';
}
When I try it, GCC 4.6.3 says it's illegal to have an non constant
expression as in 'i.get<j>'. Are there any workarounds for this one?
While I realize that you're just using this to investigate working with
tuple types in general, certainly boost tuple already handles IO. You
can do for example:
#include "boost/tuple/tuple_io.hpp"
int main() // untested
{
typedef boost::tuple<int, int, int> tuple3;
std::vector<tuple3> tuples;
tuples.push_back(tuple3(1, 2, 3));
tuples.push_back(tuple3(7, 8, 9));
tuples.push_back(tuple3(4, 5, 6));
for (auto& i : tuples)
{
using namespace boost::tuples;
std::cout << set_delimiter(' ') << set_close('\n') << i;
}
return 0;
}
As others have stated, you are mixing compiletime and runtime
polymorphism. This is boost fusion's realm.
#include <boost/fusion/adapted/boost_tuple.hpp>
#include <iostream>
struct print //some polymorphic callable function type
{
typedef void result_type;
std::ostream& mos;
print(std::ostream& os) : mos(os) {}
template<typename T> void operator()(const T& t) const
{
mos << t << ' ';
}
};
int main() // untested
{
typedef boost::tuple<int, float, std::string> tuple3;
std::vector<tuple3> tuples;
tuples.push_back(tuple3(1, 2.1f, '3'));
tuples.push_back(tuple3(7, 8.1f, '9'));
tuples.push_back(tuple3(4, 5.1f, '6'));
for (auto& i : tuples)
{
boost::fusion::for_each(i, print(std::cout));
std::cout << '\n';
}
return 0;
}