带有运算符的好奇重复模板
我可以在 G++ 上运行,但在 Visual Studo 2008 上无法编译。
template<typename T, typename DerivedT >
struct Foo
{
template<typename Scale>
DerivedT operator * (const Scale i)
{
DerivedT result;
return result;
}
};
template<typename T>
struct Bar : public Foo<T, Bar<T> >
{
// Removing this operator gets rid of the error.
Bar& operator * (const Bar& boo)
{
return *this;
}
};
int main()
{
Bar<float> bar;
bar = bar * 3;
return 0;
}
我收到错误
Error 1 error C2679: binary '*' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
即使我将 Foo 运算符显式定义为 int/double/float ,它也会返回相同的错误消息。有什么办法可以克服这个吗?
编辑: 仅当派生类重载也在基类中定义的运算符 * 时,这种情况才会崩溃。
I have this working on G++ but on Visual Studo 2008 this will not compile.
template<typename T, typename DerivedT >
struct Foo
{
template<typename Scale>
DerivedT operator * (const Scale i)
{
DerivedT result;
return result;
}
};
template<typename T>
struct Bar : public Foo<T, Bar<T> >
{
// Removing this operator gets rid of the error.
Bar& operator * (const Bar& boo)
{
return *this;
}
};
int main()
{
Bar<float> bar;
bar = bar * 3;
return 0;
}
I get the error
Error 1 error C2679: binary '*' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
Even if I define the Foo operator as an int/double/float explicitly it returns the same error message. Is there any way of getting past this?
EDIT:
This only falls apart when the derived class overload the operator * that is also defined in the Base class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道你是如何通过 g++ 编译这个的(我实际上对此表示怀疑),但你的代码确实由于相当明显的原因无法编译。您的
Bar
类仅公开一个运算符 *
,并且该运算符需要一个
Bar
对象作为右侧大小的操作数。3
不起作用,3
不是Bar
并且不能转换为Bar
。基类的
运算符 *
可能在这里起作用,但它被派生类的运算符隐藏了。这就是为什么,正如人们所期望的,删除派生类的operator *
可以消除错误。您只需将 添加
到
Bar
的定义中即可取消隐藏基类的运算符,并且它应该可以编译。I don't know how you managed to compile this by g++ (and I actually doubt that), but your code is indeed not compilable for rather obvious reasons. Your
Bar
class exposes only oneoperator *
and that operator expects a
Bar
object as a right-hand size operand.3
will not work,3
is notBar
and is not convertible toBar
.The base class's
operator *
is the one that might have worked here, but it is hidden by the derived class's operator. This is why, as one would expect, removing the derived class'soperator *
gets rid of the error.You can simply add the
to the definition of
Bar
to unhide the base class's operator and it should compile.