模板类的模板操作员需要访问其他专业
Template operator of a template class requires access to other specialisations
我已经使用CRTP实现了一个矩阵类。对于矩阵乘法,我想使用friend operator*
。问题是,根据这个问题和我自己的经验,我需要在类中定义operator*
才能使其工作。
然而,这意味着我必须重新使用定义中的类模板参数,这只允许访问计算中涉及的三个矩阵中的一个。我似乎无法为别人提供友谊。
代码示例:
template<template<unsigned, unsigned> class Child, unsigned M, unsigned N>
class BaseMatrix
{
// This works, but does not give access to rhs or to the return value
template<unsigned L>
friend Child<M, L> operator*(const BaseMatrix<Child, M, N>& lhs, const BaseMatrix<Child, N, L>& rhs)
{
Child<M, L> result;
result.v = lhs.v + rhs.v; // demo, of course
return result;
}
// This compiles, but does not do anything
template<template<unsigned, unsigned> class Child2, unsigned M2, unsigned N2, unsigned L>
friend Child2<M2, N2> operator*(const BaseMatrix<Child2, M2, L>&, const BaseMatrix<Child2, L, N2>&);
// This produces an ambiguous overload
template<unsigned L>
friend Child<M, N> operator*(const BaseMatrix<Child, M, L>& lhs, const BaseMatrix<Child, L, N>& rhs);
double v;
};
template<unsigned M, unsigned N>
class ChildMatrix : public BaseMatrix<ChildMatrix, M, N>
{
};
int main()
{
ChildMatrix<3, 4> a;
ChildMatrix<4, 5> b;
ChildMatrix<3, 5> c = a * b;
return 0;
}
如何在此处防止对rhs.v
和result.v
的访问冲突错误?
不要为此使用friend
。矩阵类应该单独公开其元素,这足以从正则(非友元)函数中进行乘法运算。
相关文章:
- 如何从其他功能C++访问参数?
- 从其他类访问类时遇到问题
- 线程消息传递或更好:在"大师班"中访问其他班级的成员
- 如何从其他结构访问受保护的结构变量
- 为什么我可以访问其他班级的私人成员?
- C++:从其他类访问结构的私有成员向量
- Unity3d 中还有其他方法可以访问设备相机吗?
- 访问从 CPP 文件到其他头文件的静态变量
- 在其他线程中循环访问该concurrent_vector时调用 concurrency::concurrent_vect
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- C++使用其他命名空间中的符号,而不使它们可从外部访问
- 变量 z 无法从其他函数访问变量 x
- 访问其他类中多个对象的私有成员向量
- 在类中使用映射并通过其他类的 get() 和 set() 函数访问值
- 访问其他线程堆栈变量如何在C++中工作?
- 访问其他网站后如何获得完整(精确)的URL / QUrl地址?
- 结构 #ifndef 灰显,其他源文件无法访问
- C++ 子类无法访问其他子类向量
- 当从其他方法返回 vector 时,C++无法访问矢量元素
- Windows 10 是否保护您不访问其他程序正在使用的内存?