I made a class for an arduino program. Inside the class I would like to toss a compiler error if a wrong pin number is passed as an argument.
class AnalogOutput : public AnalogBlock
{
public:
AnalogOutput( uint8_t _pin ) : pin( _pin )
{
static_assert
( pin == 3
|| pin == 5
|| pin == 6
|| pin == 9
|| pin == 10
|| pin == 11 , "INVALID PWM PIN USED"
) ;
}
void run()
{
if( IN2 != prevIn )
{ prevIn = IN2 ; // if incoming change, update PWM level
analogWrite( pin, IN2) ;
}
}
private:
const uint8_t pin ;
uint8_t prevIn ;
} ;
The constructor is only called with compile-time constants.
static ServoMotor M1 = ServoMotor( 3 ) ; // 3 is the pin number
Yet I get me this compiler error
error: non-constant condition for static assertion
static_assert (
^~~~~~~~~~~~~
error: use of 'this' in a constant expression
I looked here but it did not make me wizer. It is the first time that I am trying to use static_assert()
.
First question: what I am trying to do, can that be done in the first place? Second question: providing that the previous answer is 'yes' how can it be done?
In responds to Erel's answer: I tried this:
template<uint8_t pin>
class AnalogOutput : public AnalogBlock
{
public:
AnalogOutput( uint8_t _pin ) : pin( _pin )
{
static_assert
(
pin == 3
|| pin == 5
|| pin == 6
|| pin == 9
|| pin == 10
|| pin == 11 , "INVALID PWM PIN USED"
) ;
}
void run()
{
if( IN2 != prevIn )
{ prevIn = IN2 ; // if incoming change, update PWM level
analogWrite( pin, IN2) ;
}
}
private:
const uint8_t pin ;
uint8_t prevIn ;
} ;
I construct an object
static AnalogInput a1 = AnalogInput(0) ;
And this give me this error
error: invalid use of template-name 'AnalogOutput' without an argument list
static AnalogOutput a1 = AnalogOutput(0) ;
I also get several notes:
note: class template argument deduction is only available with -std=c++1z or -std=gnu++1z
note: 'template<unsigned char pin> class AnalogOutput' declared here
class AnalogOutput : public AnalogBlock
^~~~~~~~~~~~
I compile with avr-gcc