繁体   English   中英

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

[英]Ambiguous template class constructor

我正在实现一个N维数组库。 考虑以下代码:

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());
    ...
}

问题是,如果Type == int ,编译器将抱怨模棱两可的构造函数调用(例如Array<1,int>(1,1) )。 是否有诸如enable_if类的技巧使编译器忽略与Rank不匹配的构造函数? (请没有C ++ 11)

谢谢

您可以为此使用模板专门化:

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
};

甚至完全将其指定为int:

template <>
class Array<2, int>
{
// Code for two-dimensional integer array
};

对于他们来说,拥有完全不同的公共接口集也是完全有效的。

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

暂无
暂无

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

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