简体   繁体   中英

Ambiguous template class constructor

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM