为什么不允许"empty attribute block"?
Why is an "empty attribute block" not allowed?
这可能是今天问的最愚蠢的问题,但无论如何我还是要继续:
具有重载操作符+=
的派生类,其基类重载操作符[]
,会产生以下编译错误:
空属性块不允许
我通常会在操作符+=
中写v[0]
和v[1]
,但是我很好奇它是否可以编译,如果不能,为什么不能。
什么是属性块?为什么编译器不将[0]
解析为[]
操作符,从基类返回引用?简单的语法问题还是更深层次的问题?
#include <array>
template<class T, int C>
struct Vec
{
typedef T value_type;
typedef unsigned index_type;
typedef unsigned size_type;
std::array<T, C> v;
template<typename ...Args>
explicit Vec(Args&&... args) : v({{args...}}) {}
Vec(std::array<T, C> const & o) : v(o) {}
value_type & operator [] (index_type i)
{
return v[i];
}
value_type const & operator [] (index_type i) const
{
return v[i];
}
};
template<class T>
struct Vec2 : Vec<T, 2>
{
template<typename ...Args>
explicit Vec2(Args... args) : Vec<T, 2>(args...) {}
Vec2(Vec2<T> const & p) : Vec<T, 2>(p.v) {}
Vec2<T> & operator += (Vec2<T> const & q)
{
[0] += q[0];
[1] += q[1];
return *this;
}
};
int main(void)
{
Vec2<int> a(10, 20);
Vec2<int> b(30, 40);
a += b;
return 0;
}
不能这样使用自由形式的操作符。必须显式地提供this
,例如(*this)[0]
。引用属性的错误消息很简单,因为[]
也可以用来表示属性。
将operator+=
改为调用operator[]
,像[0]
这样的语句不是有效的c++。
Vec2<T> & operator += (Vec2<T> const & q)
{
operator[](0) += q[0];
operator[](1) += q[1];
return *this;
}
相关文章:
- C++ variable_name.attribute = x
- 需要帮助调试"attribute parser"!C++ 来自黑客排名的问题
- 为什么我需要在以下示例中在 block_cache.h 之前包含 block_cache_key.h 和 block.h
- 什么 clang-format 相当于 rustfmt 的 indent_style=Block?
- 如何定义此"if block"中其他无效输入的值,以便在c ++中将字符串转换为对象?
- C++生成器 10.2 基于函数的优化状态"unknown attribute 'optimize' ignored"
- de if-Block 是什么意思
- 禁止显示"use of the 'X' attribute is a C++17 extension"警告
- C++14 类函数错误:"Object has no attribute 'value'"
- Eigen::MatrixXd.block assignment using a std::vector
- "Attribute is protected within this context"继承和 .h 和.cpp文件
- base64 decode with openssl BIO block by block
- "Do not change a loop variable inside a for loop block"的意义是什么?
- Metis - Block output
- 将 .block() 与复矩阵 eigen lib 一起使用
- 使用block()在分配中使用block()缩小矩阵
- 如何运行由 Code::Block 创建的控制台应用程序
- 如何从特征矩阵中获取不连续的数据"block"?
- 使用 Python.h 时"AttributeError: 'module' object has no attribute 'argv'"
- 为什么不允许"empty attribute block"?