Reputation: 35
Good day! Please help me for my code, I try to make constexpr class with const pointer to non-constant and change non-constant variable in future, my compilator says
"error: ‘Actuator{const Pin{1ul, 1ul}, const Pin{1ul, 2ul}, const Pin{1ul, 3ul}, ((velocity_type*)(& velocity))}’ is not a constant expression"
,
Object act1 always life, because its code for ARM embedded device
Code:
#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);
}
Upvotes: 1
Views: 150
Reputation: 13988
According to c++ standard [expr-const]/2 (emphasis mine)
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))
is definitely a form of reinterpret casting so it cannot be used in constant expression...
Upvotes: 1