Reputation: 269
I'm implementing a N-dimensional array library. Consider this code:
template<int Rank, class Type>
class Array {
{
public:
// constructor for vectors, valid when Rank==1
Array(int dim0, Type val = Type());
// constructor for matrices, valid when Rank==2
Array(int dim0, int dim1, Type val = Type());
...
}
The problem is that if Type == int
, the compiler will complain about ambiguous constructor call (for example, Array<1,int>(1,1)
). Is there a trick like enable_if
that makes the compiler ignore constructors that don't match Rank
? (without C++11 please)
Thank you
Upvotes: 0
Views: 283
Reputation: 7353
You could use template specialization for this:
template<int size, class Type>
class Array {
// General stuff for size > 2, if you have any
};
template <class Type>
class Array<1, Type>
{
// Code for one-dimensional array
};
template <class Type>
class Array<2, Type>
{
// Code for two-dimensional array
};
or even specify it for int exactly:
template <>
class Array<2, int>
{
// Code for two-dimensional integer array
};
It is also perfectly valid for them to have totally different set of public interfaces.
But I would probably pass an array or std::vector
of given size for dimensions or remove the third argument, just add a method, say, populate(Type t)
to do the trick (and it may be also useful not only for constructing).
Upvotes: 1