Can temporary array as argument.

P

Peng Yu

Hi,

It seems that an temporary can not be an argument. Since the last two
statements below does not work. I have to have declare one array and
then initialized an A object with the array, which is cumbersome. I'm
wondering if there is any walkaround, or I have to until the new C++
standard?

Thanks,
Peng

#include <vector>
#include <iostream>

template <typename T>
class A {
public:
template <size_t N>
A(const T(&v)[N]) {
for(size_t i = 0; i < N; ++ i)
_v.push_back(v);
}
private:
std::vector<T> _v;
};

int main() {
double v[] = {0, 1, 2, 3 };
A<double> a1(v);
A<double> a2 = v;
A<double> a3 = {0, 1, 2, 3};//error
A<double> a4({0, 1, 2, 3});//error
}
 
M

mqrk

Hi,

It seems that an temporary can not be an argument. Since the last two
statements below does not work. I have to have declare one array and
then initialized an A object with the array, which is cumbersome. I'm
wondering if there is any walkaround, or I have to until the new C++
standard?

Thanks,
Peng

#include <vector>
#include <iostream>

template <typename T>
class A {
public:
template <size_t N>
A(const T(&v)[N]) {
for(size_t i = 0; i < N; ++ i)
_v.push_back(v);
}
private:
std::vector<T> _v;

};

int main() {
double v[] = {0, 1, 2, 3 };
A<double> a1(v);
A<double> a2 = v;
A<double> a3 = {0, 1, 2, 3};//error
A<double> a4({0, 1, 2, 3});//error

}


I thought of a workaround, but requires enormous amounts of repetitive
code.

//Basically it would look like this in use:

A<double> a( bx(0.0, 1.0, 2.0, 3.0).a );

//And it would be implemented like this:

template <class, int> struct ArrayWrapper;

template <class T>
struct ArrayWrapper<T, 1>
{
T a[1];
ArrayWrapper( T t0 )
{
a[0] = t0;
}
};

template <class T>
struct ArrayWrapper<T, 2>
{
T a[2];
ArrayWrapper( T t0, T t1 )
{
a[0] = t0;
a[1] = t1;
}
};

// etc. up to ArrayWrapper<T, 10> maybe

template <class T>
ArrayWrapper< T, 1 > bx( T t0 )
{
return ArrayWrapper< T, 1 >( t0 );
}

template <class T>
ArrayWrapper< T, 2 > bx( T t0, T t1 )
{
return ArrayWrapper< T, 2 >( t0, t1 );
}

//etc.

I can't imagine the problem is so cumbersome as to warrant this
monstrosity, but I thought I'd throw it out there for you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top