I’m designing an API for embedded programming registers, in which many functions let you choose between e.g 3 values to set certain bits to. Therefore I’d like to the function to take an enum for these values with meaningful names. But I don’t see a way to avoid repeating the enum’s “path”, either namespace or class, when addressing the value:
USB2_OTG_FS::hostPortControl.setPortSpeed(USB2_OTG_FS::HostPortControl::PortSpeed::FullSpeed)
Ideally, I would like to be able to write
USB2_OTG_FS::hostPortControl.setPortSpeed(PortSpeed::FullSpeed)
// 'setPortSpeed' could be just 'set' with overloads
But that would require the scope the method belongs to to be automatically used by the parameter scope, a form of ‘method dependant argument lookup’, which isn’t a C++ feature.
I was wondering how well and how such a thing could be emulated, to avoid both the user having to clutter their scope with using
s, and not have verbose repetitive calls whenever these calls involve enums.
PS – underlying structure pseudocode:
namespace USB2_OTG_FS {
class HostPortControl {
public:
enum class PortSpeed {
FullSpeed = 0b01
};
void setPortSpeed(PortSpeed portSpeed);
} hostPortControl;
}
13
Since your enum class
is enclosed inside a class, this doesn’t solve the problem (note that before an edit this was not clear):
using USB2_OTG_FS::HostPortControl::PortSpeed;
But small tweak to this solution and it works as desired:
void test(USB2_OTG_FS::HostPortControl& a, USB2_OTG_FS::HostPortControl& b)
{
using PortSpeed = USB2_OTG_FS::HostPortControl::PortSpeed;
a.setPortSpeed(PortSpeed::FullSpeed);
b.setPortSpeed(PortSpeed::FullSpeed);
USB2_OTG_FS::hostPortControl.setPortSpeed(PortSpeed::FullSpeed);
}
Note this is placed in the scope of a function, so this impacts only this function not the whole code.
And since C++20 you can push this even further with using enum
:
void test(USB2_OTG_FS::HostPortControl& a, USB2_OTG_FS::HostPortControl& b)
{
using enum USB2_OTG_FS::HostPortControl::PortSpeed;
a.setPortSpeed(FullSpeed);
b.setPortSpeed(FullSpeed);
USB2_OTG_FS::hostPortControl.setPortSpeed(FullSpeed);
}