以下是行和列的動態數我矩陣類的一部分,這個類行主要爲了存儲矩陣元素使用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
如果分配器對你來說不是那麼重要,那麼它可以工作,如果你把它分開。 –