如何避免const版本函数的代码重复
How to avoid code duplication for const versions of functions
pointer operator->()
{
return ptr_+buffer_position_;
}
const_pointer operator->() const
{
return ptr_+buffer_position_;
}
所以const重载返回一个const指针(耶),但这两个函数做同样的事情(嘘)如何避免代码重复和随后的拷贝传递,同时仍然保持const正确性?
(我特别关注c++ 98…尽管c++ 11的答案会显得有些教化,因为我怀疑他们已经解决了这个问题)
如果您不使用c++11:
你可以试试:
class T {
pointer operator->()
{
return const_cast<pointer> (static_cast<const T*>(this)->operator->());
}
const_pointer operator->() const
{
return ptr_+buffer_position_;
}
};
相关文章:
- 代码在main()中运行,但在函数中出现错误
- 为什么我在使用void函数时得到错误代码C2276
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 这个c++代码是如何在没有定义函数的情况下运行的
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 了解每月第一天函数的代码
- 代码的效率. 转到和函数调用
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 如何定义一个没有重复代码的继承的 const 类成员函数?
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 以下代码中的函数模板有什么问题?
- 为什么这些代码仍然使用 lvalue 函数?
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 为什么下面带有非常量转换函数的代码没有歧义?
- C++代码停止工作错误使用cout内部函数
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 如何在c++中重用代码(函数)
- 编译来自学习现代 3D 图形编程的失败代码 函数___tmainCRTStartup中引用未解析的外部符号_main
- 混合代码-函数成员指针