我想将我的模板类分成 2 个文件,就像普通类如何使用 .hpp(声明所在)和 .ipp(实现所在)一样发挥作用。
我已经用正常方法做到了这一点。但对于本身就是模板的方法,我面临着一些问题。
使用以下结构:
#ifndef MATRIX_HPP
#define MATRIX_HPP
#include <array>
#include <type_traits>
template<typename t,
std::size_t m,
std::size_t n>
class Matrix
{
static_assert(std::is_arithmetic<t>::value,
"Matrix can only be declared with a type where std::is_arithmetic is true.");
public:
Matrix();
template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
Matrix<t, p, q> slice() const;
private:
std::array<std::array<t, n>, m> data{};
};
#include "Matrix.ipp"
#endif
矩阵.ipp:
#include "Matrix.hpp"
template<typename t, std::size_t m, std::size_t n>
Matrix<t, m, n>::Matrix()
{}
template<typename t,
std::size_t m,
std::size_t n,
std::size_t y,
std::size_t x,
std::size_t p,
std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{
auto mat = Matrix<t, p, q>();
for (std::size_t i = y; i < m; i++)
{
for (std::size_t j = x; j < n; j++)
{
mat[i - y][j - x] = (*this)[i][j];
}
}
return mat;
}
主.cpp
#include "Matrix.hpp"
int main() {
auto m = Matrix<3, 3, int>();
auto sliced = m.template slice<1, 1, 2, 2>();
return 0;
}
现在,当我编译它时,它失败并显示以下消息:
../Matrix.ipp:14:17: error: prototype for ‘Matrix<t, p, q> Matrix<t, m, n>::slice() const’ does not match any in class ‘Matrix<t, m, n>’
Matrix<t, p, q> Matrix<t, m, n>::slice() const
^~~~~~~~~~~~~~~
In file included from ../main.cpp:0:0:
../Matrix.hpp:20:18: error: candidate is: template<class t, long unsigned int m, long unsigned int n> template<long unsigned int y, long unsigned int x, long unsigned int p, long unsigned int q> Matrix<t, p, q> Matrix<t, m, n>::slice() const
Matrix<t, p, q> slice() const;
我不知道如何处理这个问题,因为编译器无法识别它。有办法解决这个问题吗?
我希望有人能帮助我。谢谢!
您需要定义两组模板参数:一组用于矩阵类模板,另一组用于矩阵类函数,不要将它们合并到一个长列表中:
template<typename t, std::size_t m, std::size_t n>
template<std::size_t y, std::size_t x, std::size_t p, std::size_t q>
Matrix<t, p, q> Matrix<t, m, n>::slice() const
{
另请注意,您的包含内容实际上是混乱的。包括“Matrix.hpp” 到 .ipp 文件中将不起作用,因为您已经包含了“Matrix.hpp”中的“Matrix.ipp”。虽然这不会导致错误。