好奇的带操作符的循环模板

Curious Recurring Template with Operators

本文关键字:循环 操作符 好奇      更新时间:2023-10-16

我已经在g++上工作了,但在Visual studio 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,它也会返回相同的错误消息。有办法过去吗?

编辑:

只有当派生类重载了在基类中也定义的操作符*时,这种方法才会失效。

我不知道您是如何设法用g++编译这个的(我实际上对此表示怀疑),但是由于相当明显的原因,您的代码确实不可编译。你的Bar类只暴露一个operator *

Bar& operator * (const Bar& boo)

,该操作符需要Bar对象作为右大小的操作数。3不能工作,3不是Bar,不能转化为Bar

基类的operator *可能在这里起作用,但它被派生类的操作符隐藏了。这就是为什么,正如人们所期望的那样,删除派生类的operator *可以消除错误。

你可以简单地添加

using Foo<T, Bar<T> >::operator *;

Bar的定义中去隐藏基类的操作符,它应该编译