【发布时间】:2021-09-01 04:38:17
【问题描述】:
我已经搜索过结果,但以下问题不是我想要的。
就我而言,我想定义自己的模板矩阵类
template<typename T>
class Matrix
{
public:
Matrix();
Matrix(const Matrix<T>&);
template<typename U> Matrix(const Matrix<U>&);
};
我知道为 T 和 U 添加约束会更好,但为了简单起见,我省略了它。当我只定义前两个构造函数时,一切顺利。
template<typename T>
Matrix<T>::Matrix()
{
}
template<typename T>
Matrix<T>::Matrix(const Matrix<T>&)
{
}
如果我尝试添加最后一个模板构造函数的定义,如下所示:
template<typename T, typename U>
Matrix<T>::Matrix(const Matrix<U>&)
{
}
g++ 编译器说
.\test.cpp:27:1: error: no declaration matches 'Matrix<T>::Matrix(const Matrix<U>&)'
27 | Matrix<T>::Matrix(const Matrix<U>&)
| ^~~~~~~~~
.\test.cpp:11:26: note: candidates are: 'template<class T> template<class U> Matrix<T>::Matrix(const Matrix<U>&)'
11 | template<typename U> Matrix(const Matrix<U>&);
| ^~~~~~
.\test.cpp:21:1: note: 'Matrix<T>::Matrix(const Matrix<T>&)'
21 | Matrix<T>::Matrix(const Matrix<T>&)
| ^~~~~~~~~
.\test.cpp:15:1: note: 'Matrix<T>::Matrix()'
15 | Matrix<T>::Matrix()
| ^~~~~~~~~
.\test.cpp:6:7: note: 'class Matrix<T>' defined here
6 | class Matrix
| ^~~~~~
似乎 C++ 将 template<typename T, typename U> 和 template<class T> template<class U> 视为不同的东西。但是,即使我猜到了这一点,我也不知道如何修复我的代码。
我不知道我是否可以使用 C++ 实现我的功能(我猜是的)。你能告诉我我想要的功能的最实用的实现吗?
【问题讨论】:
-
我知道定义中的
template<typename T> template<typename U> Matrix<T>::Matrix(const Matrix<U>&)会通过编译,但我不知道这是否是正确的方法。对于template<typename T> template<typename U> requires std::is_convertible_v<U, T>之类的代码,添加它会更加令人困惑