【问题标题】:Templates and lose of information模板和信息丢失
【发布时间】:2012-08-19 12:35:51
【问题描述】:

我创建了一个矩阵类:

template <typename T>
class Matrix
{
public:
    Matrix(size_t n_rows, size_t n_cols);
    Matrix(size_t n_rows, size_t n_cols, const T& value);

    void fill(const T& value);
    size_t n_rows() const;
    size_t n_cols() const;

    void print(std::ostream& out) const;

    T& operator()(size_t row_index, size_t col_index);
    T operator()(size_t row_index, size_t col_index) const;
    bool operator==(const Matrix<T>& matrix) const;
    bool operator!=(const Matrix<T>& matrix) const;
    Matrix<T>& operator+=(const Matrix<T>& matrix);
    Matrix<T>& operator-=(const Matrix<T>& matrix);
    Matrix<T> operator+(const Matrix<T>& matrix) const;
    Matrix<T> operator-(const Matrix<T>& matrix) const;
    Matrix<T>& operator*=(const T& value);
    Matrix<T>& operator*=(const Matrix<T>& matrix);
    Matrix<T> operator*(const Matrix<T>& matrix) const;

private:
    size_t rows;
    size_t cols;
    std::vector<T> data;
};

现在我想启用不同类型的矩阵之间的运算,例如:

Matrix<int> matrix_i(3,3,1); // 3x3 matrix filled with 1
Matrix<double> matrix_d(3,3,1.1); // 3x3 matrix filled with 1.1

std::cout << matrix_i * matrix_d << std::endl;

我想这样做(是正确的方式吗?):

template<typename T> // Type of the class instantiation
template<typename S>
Matrix<T> operator*(const Matrix<S>& matrix)
{
   // Code
}

如果我将双精度矩阵与整数矩阵相乘,我认为这会很好:我将获得一个新的双精度矩阵。问题是,如果我将整数矩阵与双精度矩阵相乘,我会丢失一些信息,因为我获得的矩阵将是一个整数矩阵......对吗?我该如何解决这个问题?

std::cout << matrix_d * matrix_i << std::endl; // Works: I obtain a 3x3 matrix full of 1.1
std::cout << matrix_i * matrix_d << std::endl; // Doesn't work: I obtain a 3x3 matrix full of 1 instead of 1.1

【问题讨论】:

    标签: c++ templates matrix c++11


    【解决方案1】:

    要做你想做的事,你需要提供一个operator*,它返回一个Matrix&lt;X&gt;,其中X是具有最大范围/最高精度的类型。

    如果你手头有 C++11 编译器,你可以使用:

    template <typename T, typename U>
    auto operator*( Matrix<T> const & lhs, Matrix<U> const & rhs) 
         -> Matrix< delctype( lhs(0,0) * rhs(0,0) ) >
    {
       Matrix< delctype( lhs(0,0) * rhs(0,0) ) > result( lhs );
       result *= rhs;
       return result;
    }
    

    假设您已将 operator*= 实现为允许与 Matrix&lt;T&gt; 的其他实例相乘的模板,并且您有一个转换构造函数。

    【讨论】:

    • 我有 C++ 编译器 (GCC 4.7)。 auto 关键字是唯一的方法吗?什么是转换构造函数?你能解释一下第三行吗?我不明白...谢谢。
    • @R.M.:C++11 不是唯一的方法,但它是最简单的。如果传入-std=c++11,g++4.7 应该支持语法。 auto-&gt; ... 一起被称为尾随返回类型,是一种将返回类型的定义推迟到函数的参数在上下文中的一种方式(这样lhsrhs 可以在decltype 表达式中使用)
    • @R.M. conversion constructor(我不认为标准这么称呼它们,但我认为这会被理解)将是一个接受不同类型参数的构造函数,有效地执行 type转换。在 C++03 中,您可以定义一个类型特征,它采用两种类型并产生提升的类型(比如int,int->intint,double->double)并在返回类型中使用该特征:@ 987654337@.
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2016-05-05
    相关资源
    最近更新 更多