Chr*_*omz 3 c++ templates vector c++11
我试图从一个将 std::vector 包装到 std::vector 的类进行隐式转换,但我不断收到此错误:
错误:从“const value_type {aka const MatrixRow}”转换为非标量类型“std::vector”
我的类 MatrixRow 定义如下:
template <typename NumericType>
class MatrixRow{
public:
// a lot of other methods here
//....
//......
explicit operator std::vector<NumericType>() {return row_;}
//...
//...
private:
std::vector<NumericType> row_;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在代码的其他部分执行以下操作时会发生错误:
std::vector<NumericType> row = obj.matrix_[0]; //obj.matrix_[0] is an object of type MatrixRow<NumericType>
Run Code Online (Sandbox Code Playgroud)
这是我第一次使用隐式转换,所以可能我不明白如何正确使用它们。我做错了什么?
由于您的运营商是explicit,您应该使用不同的语法:
std::vector<NumericType> row(obj.matrix_[0]);
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以返回 const 引用以避免复制:
explicit operator const std::vector<NumericType>&() const {return row_;}
Run Code Online (Sandbox Code Playgroud)