好奇的带操作符的循环模板
Curious Recurring Template with Operators
我已经在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
的定义中去隐藏基类的操作符,它应该编译
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 如何使用new操作符创建对象并使用for循环
- 好奇的带操作符的循环模板