【问题标题】:How to define a constructor of a template class C with template argument float with template parameters that can be cast to float?如何使用模板参数浮动定义模板类 C 的构造函数,模板参数可以转换为浮动?
【发布时间】: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&lt;typename T, typename U&gt;template&lt;class T&gt; template&lt;class U&gt; 视为不同的东西。但是,即使我猜到了这一点,我也不知道如何修复我的代码。

我不知道我是否可以使用 C++ 实现我的功能(我猜是的)。你能告诉我我想要的功能的最实用的实现吗?

【问题讨论】:

  • 我知道定义中的template&lt;typename T&gt; template&lt;typename U&gt; Matrix&lt;T&gt;::Matrix(const Matrix&lt;U&gt;&amp;) 会通过编译,但我不知道这是否是正确的方法。对于template&lt;typename T&gt; template&lt;typename U&gt; requires std::is_convertible_v&lt;U, T&gt; 之类的代码,添加它会更加令人困惑

标签: c++ templates


【解决方案1】:

您使用了错误的语法。

你可以使用类似下面的东西

template <typename T> struct Matrix {
    Matrix();
    template <typename U>
    Matrix(const Matrix<U>&) requires(std::is_convertible_v<U, T>);
};

template <typename T>
template <typename U>
Matrix<T>::Matrix(const Matrix<U>& rhs) requires(std::is_convertible_v<U, T>) {
    if constexpr (std::is_same_v<T, U>) {
    } else {
    }
}

【讨论】:

  • 非常感谢~我没有意识到如果U == T我的代码会导致问题。
  • template &lt;typename U&gt; Matrix(const Matrix&lt;U&gt;&amp;) 不是复制构造函数;拥有Matrix(const Matrix&lt;T&gt;&amp;); 很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2018-05-18
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多