Re: Can temporary array as argument.
On Sep 11, 4:48 pm, Peng Yu <PengYu...@gmail.com> wrote:
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[i]);
}
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.