constexpr 类中的 c++ 常量指针

标签 c++ pointers reference constexpr

美好的一天!请为我的代码提供帮助,我尝试使用指向非常量的 const 指针创建 constexpr 类,并在将来更改非常量变量,我的编译器说

“错误:‘Actuator{const Pin{1ul, 1ul}, const Pin{1ul, 2ul}, const Pin{1ul, 3ul}, ((velocity_type*)(& velocity))}”不是常量表达式",

对象 act1 始终存在,因为它的代码用于 ARM 嵌入式设备

代码:

#include <cstddef>

typedef std::size_t port_type;
typedef std::size_t pin_type;
typedef std::size_t velocity_type;

class Pin {
private:
    port_type const _port;
    pin_type const _pin;

public:
    constexpr Pin(port_type const port, pin_type const pin) :
            _port { port }, _pin { pin } {
    }
};

class Actuator {
private:
    Pin const _enable_pin;
    Pin const _dir_pin;
    Pin const _step_pin;
    velocity_type* const _velocity; //constant pointer to non-constant variable

public:
    constexpr Actuator(Pin const ep, Pin const dp, Pin const sp, const velocity_type velocity) :
            _enable_pin { ep }, _dir_pin { dp }, _step_pin { sp }, _velocity(const_cast<velocity_type*>(&velocity)) {
    }
    void set_velocity(const velocity_type velocity) const {*_velocity = velocity;} //try to change velocity
};

int main() {
    constexpr Actuator act1 ( Pin { 1, 1 }, Pin { 1, 2 }, Pin { 1, 3 }, 1u );
    act1.set_velocity(1u);
}

最佳答案

根据c++标准[expr-const]/2 (强调我的)

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:
(...)
15. a reinterpret_­cast

((velocity_type*)(& velocity)) 绝对是一种重新解释转换的形式,因此它不能用于常量表达式...

关于constexpr 类中的 c++ 常量指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43767646/

相关文章:

c++ - C++ 中的精确定时器队列

c - unsigned 和 signed int 指针之间的区别

reference - `mut a: &T` 和 `a: &mut T` 有什么区别?

c++ - STL列表题C

c++ - 错误: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’

reference - 在 Rust 中将 Vec<Box<Foo>> 转换为 &[&Foo]

c++ - 是基类型的有符号/无符号部分还是限定符

c++ - 在 C++ 中保存指向文件的指针

c++ - 函数包装器初始化在 C++11 中如何工作?

c - 使用指针构建链表