Boost logo

Boost :

From: joaquin_at_[hidden]
Date: 2008-05-21 03:05:50


Lars Schouw escribió:
> I tried to use boost::tuple for the first time, and soon ran into a problem.
>
> I can't get values using boost::get<i> where i is an int.
>
> samplec code
>
> typedef boost::tuple<double,double,double> tuple;
>
> void foo()
> {
> std::vector<tuple> corr = boost::assign::tuple_list_of ( 1.0, 0.1, -0.1 ) ( 0.1, 1.0, 0.4 ) ( -0.1, 0.4, 1.0 );
>
> for (int i = 0; i < 3; i++)
> for (int j = 0; j < 3; j++)
> {
> double val = boost::get<i>( corr[j] );
> }
> }
>
> Using Visual Studio 2005 this comes give me a compiler error:
> error C2971: 'boost::tuples::get' : template parameter 'N' : 'i' : a local
> variable cannot be used as a non-type argument
>
> then when I move the int i declaration outside of the function foo.
> I get a new error:
> error C2975: 'N' : invalid template argument for 'boost::tuples::get',
> expected compile-time constant expression
>
> What do I need to do to access values in a tuple with an index i?
>
>

Hello Lars,

The problem is that you can't do that for very fundamental reasons. As
GCC correctly
complains about, i in get<i> must be a compile-time constant, not some
value that can change
during the execution of the program. To see why, consider the case where
your tuple
type had been defined as:

  // component 1 is not a double bout a char*
  typedef boost::tuple<double,char*,double> tuple;

Now, take a look again at the expression:

  double val = boost::get<i>(corr[j]));

What happens when i==1? The compiler cannot know in advance what values i
will take, so it demands that i be a compile-time constant so as to be
able to do its
type checking.

In your particular case where all the component types are the same, you
can consider
replacing the tuple with boost::array.

HTH,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk