我有一个模板类,上面定义了一个强制转换运算符。当我为定义独立的重载时,这似乎没有按预期方式工作operator+
。
template <class TT>
class Mtx
{
private:
MtxView<TT> m_view;
public:
operator const MtxView<TT> &() const { return m_view; }
operator MtxView<TT>() { return m_view; }
...
};
template <class TT> Mtx<TT> operator+(const MtxView<TT> &m1, const MtxView<TT> &m2)
{...}
在下面的测试代码中,使用“ +”时出现编译错误,该错误是“二进制表达式的无效操作数”。我本来希望强制转换运算符可以使它正常工作。为什么会失败,以及如何解决(没有的子类MtxView
)?
Mtx<float> m1, m2, m3;
...
m1 = m2 + m3;
g ++提供了更好的错误消息(OT:可能是任何人第一次这样说)
e.cc:22:10: note: candidate is:
e.cc:16:29: note: template<class TT> Mtx<TT> operator+(const MtxView<TT>&, const MtxView<TT>&)
template <class TT> Mtx<TT> operator+(const MtxView<TT> &m1, const MtxView<TT> &m2)
^
e.cc:16:29: note: template argument deduction/substitution failed:
e.cc:22:12: note: 'Mtx<float>' is not derived from 'const MtxView<TT>'
m1 = m2 + m3;
^
由于14.8.1 / 6,模板推导失败:
如果参数类型不包含参与模板参数推导的模板参数,则对函数参数执行隐式转换(条款4)以将其转换为相应的函数参数的类型
用通俗易懂的语言说,执行TT
功能模板的参数推导时不考虑隐式转换运算符template<typename TT> U operator+(
...
因此,编译器无法推断出TT
应为哪种类型。
MM的解决方案(现已删除)之所以有效operator+
,是因为没有功能模板。TT
由于您正在调用的成员函数这一事实而已众所周知Mtx<float>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句