Re: tuples in C++11
On 8/14/2012 2:17 PM, Single Stage to Orbit wrote:
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?
No, there are no work-arounds. But this really have nothing to do with
tuples or C++ 11.
You will get the same/similar error in this code:
#include <iostream>
template<int i> int foo() { return i*42; }
int main() {
for (int j = 0; j < 3; ++j)
std::cout << foo<j>() << std::endl;
}
The template argument for 'foo' can only be a const expression. A
run-time expression ('j') cannot be used.
You *could* write an adapter function, something like
template<class Tup> int Tget(Tup const& tup, int j)
{
switch (j)
{
case 0: return tup.get<0>();
case 1: return tup.get<1>();
....
}
and then use it
std::cout << Tget(i, j) << ...
but that kind of defeats the purpose, doesn't it?
V
--
I do not respond to top-posted replies, please don't ask