具有非类型参数的 class 的非类型参数的成员函数的部分特化
Partial specialisation of member function with non-type parameter of a class with non-type parameter
我有一个矩阵 class 和 toString()
方法:
template <typename T, int rowCount, int columnCount>
class Matrix
{
//...
public:
std::string toString() const
{
// ...
}
};
现在我想专门针对 toString()
的情况,即 T
是 Matrix
以便它 returns 一个不同格式的字符串
Matrix<Matrix<double, 2, 2>, 3, 3> a;
std::string s = a.toString();
说这个案例:
Matrix<double, 2, 2> a;
std::string s = a.toString();
我试过这样的东西
template <int rows, int cols>
template <typename X, int rows_inside, int cols_inside>
std::string Matrix<Matrix<X, rows_inside, cols_inside>, rows, cols>::toString() const
{
//...
}
但它不起作用。
如何实现这种效果?
您可以使用 if constexpr
来实现。
template <typename, int, int>
class Matrix;
template <typename>
struct IsMatrix : std::false_type
{
};
template <typename T, int N, int M>
struct IsMatrix<Matrix<T, N, M>> : std::true_type
{
};
template <typename T, int rowCount, int columnCount>
class Matrix
{
//...
public:
std::string toString() const
{
if constexpr (IsMatrix<T>::value)
{
return "matrix";
}
else
{
return "not matrix";
}
}
};
我有一个矩阵 class 和 toString()
方法:
template <typename T, int rowCount, int columnCount>
class Matrix
{
//...
public:
std::string toString() const
{
// ...
}
};
现在我想专门针对 toString()
的情况,即 T
是 Matrix
以便它 returns 一个不同格式的字符串
Matrix<Matrix<double, 2, 2>, 3, 3> a;
std::string s = a.toString();
说这个案例:
Matrix<double, 2, 2> a;
std::string s = a.toString();
我试过这样的东西
template <int rows, int cols>
template <typename X, int rows_inside, int cols_inside>
std::string Matrix<Matrix<X, rows_inside, cols_inside>, rows, cols>::toString() const
{
//...
}
但它不起作用。
如何实现这种效果?
您可以使用 if constexpr
来实现。
template <typename, int, int>
class Matrix;
template <typename>
struct IsMatrix : std::false_type
{
};
template <typename T, int N, int M>
struct IsMatrix<Matrix<T, N, M>> : std::true_type
{
};
template <typename T, int rowCount, int columnCount>
class Matrix
{
//...
public:
std::string toString() const
{
if constexpr (IsMatrix<T>::value)
{
return "matrix";
}
else
{
return "not matrix";
}
}
};