以下是行和列的动态数我矩阵类的一部分,这个类行主要为了存储矩阵元素使用std::vector
。MSVC 2015年选择不正确的构造函数重载的std ::矢量
dynamic_matrix
template<typename _Ty,
class _Alloc = std::allocator<_Ty>
> class dynamic_matrix {
public:
typedef _Ty value_type;
typedef std::size_t size_type;
typedef _Alloc allocator_type;
// various other typedefs, not relevant here...
explicit dynamic_matrix(size_type _rows, size_type _cols, const _Alloc& alloc = _Alloc())
: mtx(_rows*_cols, alloc), rows_(_rows), cols_(_cols) {}
explicit dynamic_matrix(size_type _rows, size_type _cols, const value_type& _val,
const _Alloc& alloc = _Alloc()) : mtx(_rows*_cols, _val, alloc), rows_(_rows), cols_(_cols) {}
// other constructors and methods omitted...
private:
std::vector<_Ty, _Alloc> mtx;
size_type rows_;
size_type cols_;
};
当我尝试使用在上面与下面的测试中示出的片段中的第一个构造来构建dynamic_matrix
,
int main(void) {
dynamic_matrix<int> dm(10,10);
}
我得到从下面的错误MSVC 2015
:
std::vector<_Ty,_Alloc>::vector(std::initializer_list<int>,const std::allocator<_Ty>&)
: cannot convert argument 2 from 'const std::allocator<_Ty>' to 'const int&'
而在GCC 6.1.0
使用下面的命令收率编译此没有警告也不错误,
g++-6.1.0 --std=c++14 -Wall -pedantic -o maintest main.cpp dynamic_matrix.h
使用在dynamic_matrix
代码段的第二个构造上述编译罚款GCC和MSVC。
问题似乎是由于某种原因,MSVC将构造函数调用mtx(_rows*_cols, alloc)
解释为这个reference中的第7个构造函数,它将解释cannot convert from const std::allocator to const int&
错误消息。看起来GCC正在按照我的意图使用上面引用的第三个构造函数。
为什么MSVC没有选择正确的构造函数,调用std::vector
而GCC是,我能做些什么来缓解呢?
如果使用'mtx {_rows * _cols,alloc}'代替会发生什么? – NathanOliver
我仍然担心同样的错误。 – ArchbishopOfBanterbury
如果分配器对你来说不是那么重要,那么它可以工作,如果你把它分开。 –