in this question:
template; Point<2, double>; Point<3, double>
Dennis and Michael noticed the unreasonable foolishly implemented constructor.
They we
Since the array is public, it is an option to omit the constructor and allow aggregate initialization (like boost::array
for example).
Point<2, int> p = {1, 2};
This is no worse than having to call a create function. (The create function might still be handy as a utility.)
In C++0x you will be able to have all sorts of coolness. For example, play with variadic templates, to have it checked at compile-time if the constructor is called with a right number of arguments. (The following could also check if the arguments ...U
are all of type T
, with some more metaprogramming fun, but it might not be absolutely necessary.)
//helper to copy variable amount of arguments into an array
namespace detail {
template
void copy_variadic(T* p, U value)
{
*p = value;
}
template
void copy_variadic(T* p, First var, Rest ...args)
{
*p = var;
copy_variadic(++p, args...);
}
} //detail
template < unsigned int dims, typename T >
struct Point {
T X[ dims ];
Point() : X{}
{
}
template
Point(U... args) {
static_assert(sizeof...(args) == dims, "Too many or too few arguments to Point constructor");
detail::copy_variadic(X, args...);
}
//...
};
(Actually, with some modifications - perfect forwarding - copy_variadic
would make a nice addition to my collection of variadic-template utilities, if someone doesn't come and point out a significantly better way.)