c++ - 避免对 volatile 和非 volatile 成员函数进行代码重复

标签 c++

在下一个示例中,如何避免为 Volatile 和非 Volatile bar++;方法编写相同的正文(foo)?

#include <iostream>

struct A { 
    int bar = 0;
    void foo() { bar++; } 
    void foo() volatile { bar++; } 
};

int main() {
    A a;
    a.foo();

    volatile A va; 
    va.foo();
}

这个问题完全是How do I remove code duplication between similar const and non-const member functions?的类比,但是由于const和非const版本不会影响编译器的优化,所以我想知道:如果对volatile应用相同的答案,那么对于volatile使用它是否效率不高,因为volatile可以使代码变慢?

最佳答案

if apply the same answer for volatile, wouldn't it be inefficient for non-volatile uses because volatile can make code slower?



是。

How to avoid writing the same body (bar++;) for volatile and non-volatile foo methods in the next example?



据我所知,具有非静态成员函数的唯一选择是将函数主体放入类似函数的宏中。

最好使用非成员(或静态成员)功能模板代替:
template<class AA>
void foo(AA& a) { a.bar++; }

这不需要重复,并且可以用volatile或non-volatile对象调用。

关于c++ - 避免对 volatile 和非 volatile 成员函数进行代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603808/

相关文章:

c++ - 创建图c++的逻辑

c++ - 当我尝试打印 vector 的内容时编译器出错?

c++ - 如何让 IntelliSense 在 Visual Studio 2008 中可靠地工作

c++ - 为什么/如何编译?

c# - 返回二维数组(在 C# 和 C++ 中)

c++ - 泛化 C++11 线程类以使用 lambda

c++ - 使用 cv::Mat image(opencv) 我如何检测物体?

c++ - 第一次创建地形

c++ - Glut:如何知道窗口何时移动?

c++ - std::map 迭代并删除 valgrind 错误