I'm working on a tuple class for C++03. I want to be able to construct it from a list, which is tricky since the tuple's length can vary.
#ifndef N_TUPLE_H
#define N_TUPLE_H
template <typename T, int N>
class N_Tuple
{
public:
N_Tuple(T values[N]);
private:
T values_[N];
};
template <typename T, int N>
N_Tuple< T, N >::N_Tuple(T values[N])
{
for (int i = 0; i != N; ++i)
values_[i] = values[i];
}
#endif
Currently, I have to do this:
int arr[] = { 0, 1, 2 };
N_Tuple< int, 3 > t(arr);
It seems clunky and not very user-friendly. Is it possible to reduce this to a single line in C++03?
Thanks in advance.
Since you are basically imitating
std::array
, just rid of the constructor:Note, in this, you have to make the
values_
public.That way you can initialize them just as you expect:
This is valid in both C++03 and C++11, no extensions of any kind (Tr1, Boost or whatever) required.
Another alternative is to hide the helper array behind a macro. The basic idea is to initialize your helper array and from there your tuple-esque array. But since you'd want the array's contents to come after in the initializing notation (var x = contents) you'd have to use something like a prolog-epilog macro which will require some repetition and you'll have to be careful with the comma in your particular type's case:
I've worked on such a solution that is compatible with both C++03 and C++11 (provided you do implement an
initializer_list
constructor for the C++11 case) without any particular requirements on the C++03 side of things.(I am not sure how would it ever be possible to do it in a single macro, since a list of elements would contain commas which are processed specially for the macro and variadic macros are not a thing in C++03)
But unless your list is short or you abbreviate the names for the prolog-epilog macros a lot, it won't likely fit in a single line.
(Moreover, it still requires copying of the data, even though for the most simple kinds of types that won't ever matter)