简体   繁体   English

模棱两可的模板类构造函数

[英]Ambiguous template class constructor

I'm implementing a N-dimensional array library. 我正在实现一个N维数组库。 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) ). 问题是,如果Type == int ,编译器将抱怨模棱两可的构造函数调用(例如Array<1,int>(1,1) )。 Is there a trick like enable_if that makes the compiler ignore constructors that don't match Rank ? 是否有诸如enable_if类的技巧使编译器忽略与Rank不匹配的构造函数? (without C++11 please) (请没有C ++ 11)

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: 甚至完全将其指定为int:

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). 但是我可能会传递给定尺寸的数组或std::vector作为维数,或者删除第三个参数,只需添加一个方法,例如populate(Type t)即可完成操作(它可能不仅对构造)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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